C#.NET — Use the conditional (ternary) operator to rewrite: int a = 1, b = 2, c = 0; if (a < b) c = a;
-
Aint a = 1, b = 2, c = 0; c = a < b ? a : 0;
-
Bint a = 1, b = 2, c = 0; a < b ? c = a : c = 0;
-
Cint a = 1, b = 2, c = 0; a < b ? c = a : c = 0 ? 0 : 0;
-
Dint a = 1, b = 2, c = 0; a < b ? return (c): return (0);
-
Eint a = 1, b = 2, c = 0; c = a < b : a ? 0;
Answer
Correct Answer: int a = 1, b = 2, c = 0; c = a < b ? a : 0;
Explanation
Introduction / Context:This item asks for an equivalent one-liner using the conditional operator ?: that mirrors the behavior of setting c based on a < b with c initialized to 0.
Given Data / Assumptions:
- Initial values: a = 1, b = 2, c = 0.
- Original logic: if (a < b) c = a; else leave c as its current value (here 0).
Concept / Approach:With c initially 0, an equivalent expression is c = a < b ? a : 0; which assigns a when true, or 0 otherwise, preserving the initial default value when false.
Step-by-Step Solution:
Recognize the two outcomes: assign a when true; keep 0 when false. Write conditional expression: c = a < b ? a : 0; This matches the effect of the given snippet with c initially 0.Verification / Alternative check:If c had a nonzero initial value, the strict equivalence would be c = a < b ? a : c;. But for the provided initialization (c = 0), c = a < b ? a : 0; is behaviorally the same.
Why Other Options Are Wrong:
- B: syntactically unusual but can work; however, option A is the standard and directly equivalent form.
- C: malformed conditional nesting; does not compile as intended.
- D: uses return in an invalid context.
- E: incorrect ternary syntax.
Common Pitfalls:Confusing a general equivalence (needing : c) with this specific snippet where c is known to be 0.
Final Answer:c = a < b ? a : 0;