Consider the following program fragment if(a > b) if(b > c) s1; else s2; s2…
2015
Consider the following program fragment
if(a > b)
if(b > c)
s1;
else s2;
s2 will be executed if
- A.
a <= b
- B.
b > c
- C.
b >= c and a <= b
- D.
a > b and b <= c
Attempted by 679 students.
Show answer & explanation
Correct answer: D
This program fragment illustrates the 'dangling else' ambiguity. The `else` clause is associated with the nearest preceding `if`, which is `if(b > c)`. For statement `s2` to execute, the outer condition `a > b` must be true. Additionally, the inner condition `b > c` must be false (meaning `b <= c`). Therefore, `s2` executes when both `a > b` and `b <= c` are true.