9.8. Assessment: Arrays 2ΒΆ
Subgoals for Evaluating Arrays
Set up array from 0 to size-1
Evaluate data type of statements against array
Trace statements, updating slots as you go
Remember assignment subgoals
- I only
- II only
- III only
- II and III
- I, II, and III
- The largest value in arr occurs only once and is in arr[0].
- The largest value in arr occurs only once and is in arr[arr.length-1].
- The largest value in arr is negative.
- The largest value in arr is 0.
- The largest value in arr occurs more than once.
- I only
- II only
- III only
- I and III only
- II and III only
- Prints the maximum value that occurs in the array nums
- Prints the index of the maximum value that occurs in the array nums
- Prints the number of times that the maximum value occurs in the array nums
- Prints the value that occurs most often in the array nums
- Prints the index of the value that occurs the most often in the array nums
Q1: The following code segments are supposed to find the maximum value in an array of integers. Assuming that the array arr
has been declared and contains valid integer values, which of the following code segments will correctly assign the maximum value in the array to the variable max
?

Q2: The following code is intended to store the largest value in the integer array arr in the variable maxVal. Which of the following best describes the conditions under which the code will not work as intended?
int maxVal = 0;
for (int val : arr) {
if (val > maxVal)
maxVal = val;
}
Q3: The following code is intended to store the sum of all the values in the integer array arr
in the variable total
. Which of the following code segments can be used to replace /* missing code */
so that the code works as intended?
int total = 0;
/* missing code */
System.out.println(total);

Q4: Assuming that nums
has been declared and initialized as an array of integer values, which of the following best describes what this code does?
int index = 0;
int count = 0;
int m = -1;
for (int outer = 0; outer < nums.length; outer++) {
count = 0;
for (int inner = outer + 1; inner < nums.length; inner++) {
if (nums[outer] == nums[inner])
count++;
}
if (count > m) {
index = outer;
m = count;
}
} // end outer for
System.out.println(index);