Home/Questions/Question:
Given the following code fragment:
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.
Explanatory Question
Question:
Given the following code fragment:
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.
👁 36 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.
Answer with Explanation
Question:
Given the following code fragment:
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");
How to use this answer better
First read the answer fully, then try to explain it in your own words. After that, open a few related questions and compare the concepts. This method helps you remember the topic for a longer time and improves exam preparation.