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?

  1. A.

    No output is displayed

  2. B.

    The program fails to compile

  3. C.

    x is greater than 20

  4. 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:

  1. x is initialized to 10.

  2. The outer condition if (x > 5) is checked. Since 10 > 5 is true, control moves inside.

  3. The inner condition if (x < 20) is checked. Since 10 < 20 is true, the statement "x is between 5 and 20" is printed.

  4. The else block is skipped entirely.

Explore the full course: Rssb Senior Computer Instructor