In C programming, rewrite the following set of statements using the conditional (ternary) operator so that the behavior is preserved: int a = 1, b; if (a > 10) b = 20;

Difficulty: Medium

Correct Answer: b = (a > 10) ? 20 : b;

Explanation:


Introduction / Context:
This question tests understanding of the conditional (ternary) operator in C and how to rewrite a simple if statement in a compact but equivalent single expression. It also checks whether you pay attention to preserving the original program behavior, including the case where the if condition is not satisfied.


Given Data / Assumptions:

    We have variables declared as int a = 1, b.
    There is an if statement: if (a > 10) b = 20;
    There is no explicit else part, so if a is not greater than 10, b should remain unchanged.
    We want to use the conditional (ternary) operator in place of the if statement.


Concept / Approach:
The conditional operator in C has the form condition ? expression1 : expression2. If condition is nonzero, expression1 is evaluated. Otherwise expression2 is evaluated. To preserve the semantics of the given if statement, we must assign 20 to b only when a is greater than 10 and leave the value of b unchanged otherwise. That means both sides of the colon need to produce a value for b, matching the original effect.


Step-by-Step Solution:
Identify the condition: a > 10. Identify the true branch effect: b should become 20. Identify the false branch effect: b should keep its previous value. Write a single assignment using the conditional operator: b = (a > 10) ? 20 : b; Check that when a is greater than 10, the expression yields 20, and when it is not, it yields the old value of b.


Verification / Alternative check:
If a is 15, the condition a > 10 is true, so the expression becomes b = 20; exactly like the original if statement. If a is 5, the condition is false, so the expression becomes b = b; which leaves b unchanged. No other side effects are introduced, so the rewritten code is behaviorally equivalent.


Why Other Options Are Wrong:
Option b uses a >= 10, which incorrectly includes the case a equals 10 and changes the behavior.
Option c reverses the branches and assigns 20 when a is not greater than 10.
Option d triggers assignment when a is less than 10, which is not what the original if statement does.


Common Pitfalls:
A common mistake is to forget the else part and write something like (a > 10) ? (b = 20) : 0; which is legal but less clear. Another error is to change the condition slightly, such as using a >= 10, which subtly changes the behavior. Always check that the false branch of the conditional leaves the variable unchanged when the original code had no else clause.


Final Answer:
The correct conditional operator form is b = (a > 10) ? 20 : b; which exactly matches the behavior of the original if statement.

More Questions from Programming

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion