Question 271
What is printed?
int[] data = {3, 7, 2, 8, 5, 1, 9, 4, 6};
int maxDiff = 0;
for (int i = 0; i < data.length - 1; i++) {
int diff = Math.abs(data[i] - data[i + 1]);
if (diff > maxDiff) {
maxDiff = diff;
}
}
System.out.println(maxDiff);Main Solution
The code iterates through consecutive pairs in the array {3, 7, 2, 8, 5, 1, 9, 4, 6} and tracks the maximum absolute difference between adjacent elements.
Let's compute each adjacent difference:
| i | data[i] | data[i+1] | |diff| | maxDiff |
|---|---|---|---|---|
| 0 | 3 | 7 | 4 | 4 |
| 1 | 7 | 2 | 5 | 5 |
| 2 | 2 | 8 | 6 | 6 |
| 3 | 8 | 5 | 3 | 6 |
| 4 | 5 | 1 | 4 | 6 |
| 5 | 1 | 9 | 8 | 8 |
| 6 | 9 | 4 | 5 | 8 |
| 7 | 4 | 6 | 2 | 8 |
The maximum absolute difference between any two adjacent elements is 8 (between data[5] = 1 and data[6] = 9). Therefore, System.out.println(maxDiff) prints 8.
The correct answer is C.
Teacher Explanation
This question tests students' ability to trace through a loop that computes the maximum absolute difference between consecutive array elements. The key insight is that the loop runs from index 0 to data.length - 2 (inclusive), comparing each element with the next. Students must correctly apply Math.abs() and track how maxDiff updates. The largest jump occurs between 1 and 9, giving a difference of 8.
Education Coach Advice
When tracing loops that track a running maximum, always complete the full trace — don't stop early. Create a small table with columns for i, data[i], data[i+1], diff, and maxDiff to avoid missing the true maximum. Also, remember that Math.abs() ensures the difference is always non-negative, so direction doesn't matter here.
Traps
Option A (6): A student might stop tracing early (after index 2, where |2−8|=6) and incorrectly conclude the answer is 6. This is a common off-by-one or early-exit tracing error.
Option B (9): A student might confuse the maximum value in the array (9) with the maximum difference, or mistakenly compute a non-adjacent pair difference.
Option D (5): A student might find the second-largest adjacent difference (|7−2|=5 or |9−4|=5) and stop there.
Answer images

