Consider the code segment written below in C++: if (count < 10) // if #1 if…
2018
Consider the code segment written below in C++: if (count < 10) // if #1 if ((count % 4) == 2) // if #2 cout << "condition; white\n"; else // (Indentation is wrong) cout << "condition is: tan\n"; There are 2 if statements and one else. To which if, the else statement belong?
- A.
It belongs to if #1
- B.
It belongs to if #2
- C.
It belongs to both the if statements
- D.
It is independent
Attempted by 149 students.
Show answer & explanation
Correct answer: B
Key point: In C/C++, an else pairs with the nearest unmatched if when braces are not used.
In the given code there are two if statements written without braces. The else therefore attaches to the inner if that tests whether (count % 4) == 2.
Outer condition: if (count < 10)
Inner condition: if ((count % 4) == 2) — this is the nearest unmatched if, so the else pairs with this one.
Example: let count = 8
First check: 8 < 10 → true
Second check: 8 % 4 == 2 → false
Because the inner condition is false while the outer is true, the else runs — demonstrating that the else belongs to the inner if.
Tip: To make the grouping explicit and avoid this ambiguity, use braces. For example, to attach else to the outer if, write the outer if with a block around its body, e.g. if (count < 10) { if ((count % 4) == 2) cout << "..."; } else cout << "...";