50.3k views
2 votes
Consider the following code segment, which is intended to print the maximum value in an integer array values. Assume that the array has been initialized properly and that it contains at least one element.

int maximum = /* missing initial value */;
for (int k = 1; k < values.length; k++)
{
if (values[k] > maximum)
{
maximum = values[k];
}
}
System.out.println(maximum);
Which of the following should replace /* missing initial value */ so that the code segment will work as intended? A
values[0]
B
values[1]
C
Integer.MIN_VALUE
D
Integer.MAX_VALUE
E

User Nilanjan
by
7.3k points

1 Answer

3 votes

Answer:

B: values[0]

Step-by-step explanation:

(From CollegeBoard)

The code segment compares each integer in the array after the first to maximum. If an integer is the maximum integer found so far, maximum is assigned that integer. By initializing maximum to values[0], the first element in the array will be the maximum integer found so far. Any subsequent integer will be compared to the maximum integer found so far, and the code segment will work as intended.

Basically, if you set the maximum value to the first item in the array, it will compare it against the rest of the values in the array. During this process, if there is a higher number in the array, it will replace the maximum until reaching the end of the array.

(Also answer A is just 0 for anyone wondering)

User Randy Olson
by
7.9k points