if (x > 10) System.out.println("Large"); else if (x > 6 && x <= 10) System.out.println("Medium"); else if (x > 3 && x <= 6) System.out.println("Small"); else System.out.println("Very small");


What is wrong, logically, with the following code?

if (x > 10) System.out.println("Large");

else if (x > 6 && x <= 10) System.out.println("Medium");

else if (x > 3 && x <= 6) System.out.println("Small");

else System.out.println("Very small");

a) There is no logical error, but there is no need to have (x <= 10) in the second conditional or (x <= 6)

in the third conditional

b) There is no logical error, but there is no need to have (x > 6) in the second conditional or (x > 3) in the

third conditional

c) The logical error is that no matter what value x is, “Very small” is always printed out

d) The logical error is that no matter what value x is, “Large” is always printed out

e) There is nothing wrong with the logic at all

Answer: a. Explanation: Because this is a nested if-else statement, if (x > 10) is true, then the first println statement is executed and the rest of the statement is skipped. If (x > 10) is not true, then the first else clause is executed and the next if condition is tested. At this point, (x > 10) is known to be false and therefore (x <= 10) must be true, so there is no need to check this inequality. Similarly, if (x > 6) is false, then the second else clause is executed and the third if condition is tested. However, (x <= 6) must be true, so there is no need to check this inequality.