Question 121
What is printed?
int[][] grid = {{3, 1, 4, 1},
{5, 9, 2, 6},
{5, 3, 5, 8}};
int maxCol = 0;
int maxSum = 0;
for (int c = 0; c < grid[0].length; c++) {
int colSum = 0;
for (int r = 0; r < grid.length; r++) {
colSum += grid[r][c];
}
if (colSum > maxSum) {
maxSum = colSum;
maxCol = c;
}
}
System.out.println(maxCol + " " + maxSum);Main Solution
To determine what is printed, trace through the code by computing the column sums of the 2D array:
| Column (c) | grid[0][c] | grid[1][c] | grid[2][c] | colSum |
|---|---|---|---|---|
| 0 | 3 | 5 | 5 | 13 |
| 1 | 1 | 9 | 3 | 13 |
| 2 | 4 | 2 | 5 | 11 |
| 3 | 1 | 6 | 8 | 15 |
Now trace the outer loop:
- c = 0: colSum = 13. Since 13 > 0 (maxSum), maxSum = 13, maxCol = 0.
- c = 1: colSum = 13. Since 13 > 13 is false, no update. maxSum = 13, maxCol = 0.
- c = 2: colSum = 11. Since 11 > 13 is false, no update.
- c = 3: colSum = 15. Since 15 > 13 is true, maxSum = 15, maxCol = 3.
After the loop, maxCol = 3 and maxSum = 15.
System.out.println(maxCol + " " + maxSum) prints: 3 15.
The correct answer is A.
Teacher Explanation
This question tests 2D array traversal and accumulation. The outer loop iterates over columns (c) and the inner loop iterates over rows (r), summing each column. The code tracks the column index with the maximum sum. Column 3 has the highest sum (15), so the output is 3 15.
Education Coach Advice
When tracing 2D array problems on the AP exam, always build a quick table of row/column sums. Pay close attention to whether the loop iterates over rows first or columns first — here the outer loop is over columns (c) and the inner is over rows (r), which is the reverse of the more common row-major traversal. Also note that the > (strict greater-than) means ties do NOT update, so the first column to achieve a given max keeps the index.
Traps
Common traps:
- Option B (0 13): A student might stop after the first column update and forget that column 3 later produces a higher sum of 15.
- Option C (1 13): A student might confuse the column index or think column 1 wins because it also sums to 13 (but column 0 updates first, and neither beats column 3).
- Option D (3 13): A student might correctly identify column 3 as the winner but miscalculate its sum as 13 instead of 15 (perhaps confusing it with columns 0 or 1).
Answer images

