if (a == 0) System.out.println("Zero");
if (a == 1) System.out.println("One");
if (a == 2) System.out.println("Two");
if (a == 3) System.out.println("Three");
Write an alternative code (using if) that saves on the number of comparisons.
if (a == 0) System.out.println("Zero");
if (a == 1) System.out.println("One");
if (a == 2) System.out.println("Two");
if (a == 3) System.out.println("Three");
Write an alternative code (using if) that saves on the number of comparisons.
Answer:
The given code performs four separate comparisons, even if one condition is already true. We can reduce the number of comparisons by using an if–else if ladder, so that once a condition is true, the rest are skipped.
if (a == 0)
System.out.println("Zero");
else if (a == 1)
System.out.println("One");
else if (a == 2)
System.out.println("Two");
else if (a == 3)
System.out.println("Three");
Explanation:
In the original code, all four if conditions are checked independently.
In the improved version, if one condition is true, the remaining else if conditions are not evaluated.
This approach reduces the number of comparisons and makes the program more efficient.
✅ Final Answer:
if (a == 0)
System.out.println("Zero");
else if (a == 1)
System.out.println("One");
else if (a == 2)
System.out.println("Two");
else if (a == 3)
System.out.println("Three");