Consider the following C code snippet. int x = 10; if (x > 5) if (x < 20)…
2025
Consider the following C code snippet.
int x = 10;
if (x > 5)
if (x < 20)
printf("x is between 5 and 20");
else
printf("x is greater than 20");
What will be the output of this code?
- A.
No output is displayed
- B.
The program fails to compile
- C.
x is greater than 20
- D.
x is between 5 and 20
Attempted by 239 students.
Show answer & explanation
Correct answer: D
In C, the else clause binds to the nearest preceding if statement. Here, 'else' attaches to 'if (x < 20)'. With x=10, both conditions are true, so the output is 'x is between 5 and 20'.
Step-by-step execution:
xis initialized to10.The outer condition
if (x > 5)is checked. Since10 > 5is true, control moves inside.The inner condition
if (x < 20)is checked. Since10 < 20is true, the statement"x is between 5 and 20"is printed.The
elseblock is skipped entirely.