C#.NET — Predict the output of the following ternary operator code: int a = 10, b = 20, c = 30; int res = a < b ? (a < c ? c : a) : b; Console.WriteLine(res);
-
A10
-
B20
-
C30
-
DCompile Error / Syntax Error
-
ENone of these
Answer
Correct Answer: 30
Explanation
Introduction / Context:This question checks understanding of the conditional (ternary) operator ?: in C#. The operator evaluates a Boolean expression and returns one of two results.
Given Data / Assumptions:
- a = 10, b = 20, c = 30
- Expression: a < b ? (a < c ? c : a) : b
Concept / Approach:Nested ternary operations must be carefully evaluated respecting parentheses and operator precedence. First the outer condition is tested, then the inner one.
Step-by-Step Solution:
Step 1: Evaluate a < b → 10 < 20 → true. So take the first branch: (a < c ? c : a). Step 2: Evaluate a < c → 10 < 30 → true. So result is c = 30. Final result: res = 30.Verification / Alternative check:Compiling and running the code outputs 30, confirming correctness.
Why Other Options Are Wrong:10 and 20 are wrong because conditions did not direct evaluation there. Compile error is wrong because syntax is valid.
Common Pitfalls:Forgetting parentheses or misunderstanding evaluation order in nested ternary operators.
Final Answer:30