In C programming, what will be the output of the following program (note the nested conditional operator and that only 'num' is printed)?
#include
int main()
{
int k, num = 30;
k = (num > 5 ? (num <= 10 ? 100 : 200) : 500);
printf("%d
", num);
return 0;
}
-
A200
-
B30
-
C100
-
D500
-
ECompiler-dependent
Answer
Correct Answer: 30
Explanation
Introduction / Context:This C output question checks understanding of the conditional (ternary) operator, operator precedence, and, most importantly, what value is actually printed. Many learners focus on the expression that computes k and forget that printf prints only num.
Given Data / Assumptions:
- num is initialized to 30.
- k is assigned using a nested conditional operator.
- The program prints num via printf("%d", num).
Concept / Approach:The ternary operator has the form condition ? expr_true : expr_false. Nested usage evaluates the inner test only when needed. However, the print statement uses only num, not k. Therefore any changes to k are irrelevant to the output.
Step-by-Step Solution:Evaluate condition: num > 5 evaluates to 30 > 5, which is true.Because true, evaluate the inner ternary: (num <= 10 ? 100 : 200). Since 30 <= 10 is false, this yields 200; thus k becomes 200.No statement modifies num; it remains 30 throughout.printf prints num, so the output is 30.
Verification / Alternative check:You can temporarily add a second printf to display k. You would then see k = 200, num = 30, confirming that only num is printed in the provided code.
Why Other Options Are Wrong:(a) 200 is the value assigned to k, not printed. (c) 100 would be chosen only if num <= 10, which is false. (d) 500 would be chosen only if num > 5 were false, which it is not. (e) The behavior is not compiler-dependent; it is well-defined.
Common Pitfalls:Confusing the value printed (num) with the computed value (k). Another pitfall is assuming the ternary expression prints or changes num, which it does not.
Final Answer:30