A nested conditional expression — Aptitude Question
A nested conditional expression: What does this C program print? Answer and worked solution on CodeKairo.
- Topic: Programming Fundamentals
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 75 seconds
Question
What does this C program print?
#include <stdio.h>
int main(void) {
int x = 3;
printf("%d", x > 2 ? x > 4 ? 100 : 200 : 300);
return 0;
}Options
- 3
- 100
- 200
- 300
Show the answer and the worked solution
Correct answer: C. 200
Worked solution
- The expression groups as x > 2 ? (x > 4 ? 100 : 200) : 300.
- x = 3, so x > 2 is true and the outer conditional selects its middle operand.
- Inside that, x > 4 is false, so the result is 200.
Answer: 200.
The idea
?: is right-associative, so an unbracketed chain nests inside the previous true branch. Adding the brackets by hand converts the puzzle into an ordinary if / else chain.
Shortcut. The inner ?: nests inside the true branch: 3 passes x > 2 and fails x > 4, so the value is the inner false branch, 200.
Common trap. 100 is picked by stopping at the first true test, x > 2, and taking the first number after a ?, without evaluating the inner x > 4.
All Programming Fundamentals questions · placement mock tests