119k views
0 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 segment NOT print the correct value?

User Arx
by
7.7k points

1 Answer

5 votes

Final answer:

The code segment fails to identify the smallest number when 'a' is less than 'b' and 'c', and an incorrect value is subtracted from the sum. For instance, with a = 1, b = 3, and c = 2, the code would wrongly subtract 'a', resulting in an incorrect sum of the greatest two values.

Step-by-step explanation:

The issue with the code segment provided is that it doesn't cover all the possible cases where the three variables a, b, and c can relate to each other. Specifically, it fails to correctly identify the smallest number when a is less than both b and c, as the else clause incorrectly sets low to a without checking if a is greater than c.

For example, if the values are a=1, b=3, and c=2, the code segment would incorrectly identify an as the lowest number to subtract from the sum, resulting in 1 + 3 + 2 - 1 which equals 5 instead of the correct answer, 3 + 2 which equals 5. It should have subtracted a, to get the sum of the two greater values, b + c.

To fix this, the conditionals must be adjusted to correctly evaluate all possible orderings of the three variables to determine the lowest value.

User Pbacterio
by
8.1k points