Question:

Read the if program segment given below:

if (a > b)
    z = 25;
else
    z = 35;

Which one of the following is the correct conversion of the if segment to ternary?

Show Hint

For converting if-else into ternary, always write: \textbf{condition ? true-part : false-part}. The first value comes from the \textbf{if} block, and the second value comes from the \textbf{else} block.
  • \(z = a>b ? 35 : 25;\)
  • \(z = a>b ? 25 : 35;\)
  • \(z = a>b : 35 ? 25;\)
  • \(z = a>b : 25 ? 35;\)
Hide Solution
collegedunia
Verified By Collegedunia

The Correct Option is B

Solution and Explanation

Ternary Operator Conversion

Step 1: Understand the given if-else statement
The logic states:
If $(a > b)$, then $z = 25$.
Otherwise, $z = 35$.
The value assigned to $z$ depends strictly on the boolean result of the condition $(a > b)$.

Step 2: Recall the syntax of the Ternary Operator
The ternary (conditional) operator follows this structure:
variable = (condition) ? value_if_true : value_if_false;

Step 3: Apply the logic to the given statement
 

  • Condition: $a > b$
  • True Value: $25$
  • False Value: $35$

Plugging these into the syntax:
z = (a > b) ? 25 : 35;

Step 4: Comparison of Options
 

  • (A): Incorrect. It reverses the values ($z = a > b ? 35 : 25$).
  • (B): Correct. Matches the original if-else logic perfectly.
  • (C) & (D): Incorrect. These typically use invalid syntax or misplaced operators.

Final Answer: 
$z = a > b ? 25 : 35;$

Was this answer helpful?
0
0

Top Questions on Control Statements

View More Questions

Questions Asked in ICSE Class X board exam

View More Questions