The Gateway to Computer Science Excellence
+6 votes

Consider the following program fragment

  if(a > b)  if(b > c)     s1;  else s2;

s2 will be executed if

  1. a <= b
  2. b > c
  3. b >= c and a <= b
  4. a > b and b <= c
in Programming by Active (2.5k points) | 2k views

5 Answers

+13 votes
Best answer

Answer: (d)

Explanation: Given program fragment is without braces, it is equivalent with braces will be like this:
if (a > b)
    if (b > c) { s1; }
    else { s2; }

Note: A expression's scope remains until its sub expressions does not complete.

Reference: Executed program on URL:

by Active (2.4k points)
selected by
similar to dangling else problem ?
Yes in the sense of someone who is new to the language. But dangling-else is a compilation issue- this problem is solved before a language is made. In C/C++ this is solved by always taking the else to the nearest if. So, as a programmer there is no problem of dangling-else and even for a compiler designer there is no problem - its solved when the language was made.
@arjun sir how can you say it is like one mention mangilal saswat it could be like this




else s2;

notice there is sno semicolon so it is not dangling else problem

@pC boss

answer would be A
+3 votes
Point here to be noted is that when I write if (a >b) now after this I haven't written any braces so anything written within it would be considered as a single statement hence it is equivalent to if(a>b){ if (b < c) {s1 ;} else {s2 ;}

therefore clearly if s2 has to execute then we must have the condition a>b to be true simultaneously with b<=c , so option D is correct .
by Loyal (6.4k points)
there can be one more possibility



       {     s1;

in this case option a is correct
This possibility is not equivalent to given program fragment. Given program assumes 'else' with internal 'if' but you have made 'else' with external 'if'.
+1 vote

C compiler parses every else statement greedily ie every else statement will match the nearest if statement. Hence the correct representation is 




Answer is D

by (299 points)
If no braces are put then only the next statement after if condition is executed if condition is true. So In this case if a>b then it will go to next command b>c else it will skip b>c follow-up statement (s1). And s2 will be executed. The program behaves in the way akash3052 has demonstrated. So option 'a' is correct.
0 votes
S2 WILL BE EXECUTED IF D)a>b and b<=c
by Active (2.1k points)
0 votes
Answer - (D)

When 1st IF is true and second IF is false then only s2 will be executed
by Loyal (9.9k points)
Quick search syntax
tags tag:apple
author user:martin
title title:apple
content content:apple
exclude -tag:apple
force match +apple
views views:100
score score:10
answers answers:2
is accepted isaccepted:true
is closed isclosed:true
50,737 questions
57,297 answers
104,977 users