4.0k views
3 votes
Assume that the int variables a, b, c, and low have been properly declared and initialized. The code segment below is intended to print the sum of the greatest two of the three values but does not work in some cases.

if (a > b && b > c)
{
low = c;
}
if (a > b && c > b)
{
low = b;
}
else
{
low = a;
}
System.out.println(a + b + c - low);

For which of the following values of a, b, and c does the code

A. a = 1, b = 1, c = 2
B. a = 1, b = 2, c = 1
C. a = 1, b = 2, c = 3
D. a = 2, b = 2, c = 2
E. a = 3, b = 2, c = 1

1 Answer

2 votes

Final answer:

The code segment fails for options C (a = 1, b = 2, c = 3) and E (a = 3, b = 2, c = 1), where the value of 'low' is incorrectly assigned due to the structure of the if-else statements. option c is the correct answer.

Step-by-step explanation:

The code segment provided is intended to print the sum of the greatest two values out of the three given integers. However, due to the lack of braces in the if-else statements, it does not always work as expected. The else clause is only connected to the second if statement, which can lead to incorrect assignment of the variable low in some scenarios.

By testing the values of a, b, and c provided in options A to E, we can determine that the code will work correctly for options A, B, and D. This is because:

  1. For A (a = 1, b = 1, c = 2), low will be assigned c and the sum will correctly print 2.
  2. For B (a = 1, b = 2, c = 1), low will be assigned c and the sum will correctly print 3.
  3. For D (a = 2, b = 2, c = 2), all numbers are equal so it doesn't matter which is assigned to low.

However, the code fails for C (a = 1, b = 2, c = 3) and E (a = 3, b = 2, c = 1) because low is incorrectly set to a in both cases, resulting in the sum of the lowest two numbers instead of the highest two.

User Giorgio Borgo
by
8.4k points