AP® Computer Science A Data Collections Practice Questions
Work through AP Computer Science A practice questions on Data Collections, then check each answer against a worked solution.
Free · no sign-up Open questions need no account. Sign up or log in to open the rest.
Subtopic: 2D Arrays Clear filter
Question 152
Question 153
Question 154
Question 155
Question 156
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
Question 157
What is printed?
int[][] m = {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
int sum = 0;
for (int r = 0; r < m.length; r++) {
for (int c = 0; c < m[0].length; c++) {
if ((r + c) % 2 == 0) sum += m[r][c];
}
}
System.out.println(sum);Main Solution
The code sums all elements m[r][c] where (r + c) % 2 == 0, i.e., where the sum of the row and column indices is even.
The 2D array is:
| c=0 | c=1 | c=2 | c=3 | |
|---|---|---|---|---|
| r=0 | 1 | 2 | 3 | 4 |
| r=1 | 5 | 6 | 7 | 8 |
| r=2 | 9 | 10 | 11 | 12 |
Check each cell for (r + c) % 2 == 0:
- (0,0): 0+0=0 ✓ → 1
- (0,1): 0+1=1 ✗
- (0,2): 0+2=2 ✓ → 3
- (0,3): 0+3=3 ✗
- (1,0): 1+0=1 ✗
- (1,1): 1+1=2 ✓ → 6
- (1,2): 1+2=3 ✗
- (1,3): 1+3=4 ✓ → 8
- (2,0): 2+0=2 ✓ → 9
- (2,1): 2+1=3 ✗
- (2,2): 2+2=4 ✓ → 11
- (2,3): 2+3=5 ✗
Sum = 1 + 3 + 6 + 8 + 9 + 11 = 38
The answer is B) 38.
Teacher Explanation
This question tests 2D array traversal and modular arithmetic. Students must identify which indices satisfy (r + c) % 2 == 0 — the "checkerboard" pattern of even-sum positions — and correctly sum the corresponding values. The total is 1 + 3 + 6 + 8 + 9 + 11 = 38.
Education Coach Advice
When tracing 2D array problems on the AP exam, draw a small grid and mark which cells satisfy the condition before summing. For a 3×4 array, there are only 12 cells to check — a quick table trace prevents arithmetic errors. Also note that (r + c) % 2 == 0 is a classic "checkerboard" pattern: it selects the "white squares" if you imagine a chessboard starting with white at (0,0).
Traps
Option A (36): A common mistake is to accidentally skip one element (e.g., forgetting m[1][3]=8 or m[2][2]=11) due to an off-by-one error in tracing the loop. Option C (42): Students might incorrectly include cells where (r + c) % 2 == 1 instead of 0, or mix up the condition. Option D (78): This is the sum of all elements in the array (1+2+...+12 = 78), which results from ignoring the if condition entirely.
Answer images
Question 158
What is printed?
int[][] grid = new int[4][4];
for (int r = 0; r < 4; r++) {
for (int c = 0; c < 4; c++) {
if (r <= c) grid[r][c] = 1;
}
}
int sum = 0;
for (int r = 0; r < 4; r++)
for (int c = 0; c < 4; c++)
sum += grid[r][c];
System.out.println(sum);Main Solution
To determine what is printed, we need to trace through the code step by step.
Step 1: Initialize the grid.
int[][] grid = new int[4][4]; creates a 4×4 grid initialized to all zeros.
Step 2: Fill the grid.
The nested loops iterate over all (r, c) pairs where r and c each range from 0 to 3. The condition if (r <= c) sets grid[r][c] = 1 whenever the row index is less than or equal to the column index. This corresponds to the upper triangle (including the diagonal) of the matrix:
| c=0 | c=1 | c=2 | c=3 | |
|---|---|---|---|---|
| r=0 | 1 | 1 | 1 | 1 |
| r=1 | 0 | 1 | 1 | 1 |
| r=2 | 0 | 0 | 1 | 1 |
| r=3 | 0 | 0 | 0 | 1 |
Step 3: Sum all elements.
Count the number of 1s: row 0 has 4, row 1 has 3, row 2 has 2, row 3 has 1. Total = 4 + 3 + 2 + 1 = 10.
Step 4: Print.
System.out.println(sum); prints 10.
The correct answer is C) 10.
Teacher Explanation
This question tests students' ability to trace nested loops and understand 2D array indexing. The key insight is recognizing that r <= c selects the upper triangular portion of the matrix (including the main diagonal). For a 4×4 matrix, the number of cells satisfying this condition is 4+3+2+1 = 10. Students must correctly initialize the grid (all zeros by default in Java) and understand that only cells meeting the condition are set to 1.
Education Coach Advice
When tracing 2D array problems on the AP exam, draw out the grid on your scratch paper and mark each cell that satisfies the condition. Then count the marked cells. This visual approach prevents off-by-one errors and helps you quickly verify your answer. Pay close attention to whether the condition uses < or <= — this single character changes the answer significantly.
Traps
Option A (16): A student might choose this if they think every cell is set to 1, forgetting the if (r <= c) condition.
Option B (6): A student might choose this if they use the condition r < c (strict less than) instead of r <= c, missing the diagonal (which adds 4 more cells).
Option D (12): A student might miscount the 1s, perhaps including one extra row or miscounting the diagonal.
Answer images
Question 159
A geographic survey team uses a 2D integer array to represent terrain elevation data. Each element stores the elevation in meters at that grid location. The team needs tools to analyze the border of the survey region and to detect notable peaks in the interior.
PART A
Write the method public int borderSum(int[][] grid) that returns the sum of all elements on the border of the grid (first row, last row, first column, last column). Each corner element is counted exactly once.
For example, if grid = {{5, 3, 8, 1}, {2, 7, 4, 9}, {6, 1, 3, 5}}, the border elements are 5, 3, 8, 1, 9, 5, 3, 1, 6, 2 and the sum is 43 (interior elements 7 and 4 are excluded).
public int borderSum(int[][] grid) {
}PART B
Write the method public int countPeaks(int[][] grid) that returns the number of interior cells (not on any edge) that are strictly greater than all four of their direct neighbors (up, down, left, right).
For example, if grid = {{1, 2, 1, 3}, {4, 8, 3, 1}, {1, 2, 9, 4}, {2, 1, 5, 2}}, the interior cells are at (1,1)=8, (1,2)=3, (2,1)=2, (2,2)=9. Cell (1,1)=8 is greater than all neighbors (2, 4, 3, 2) → peak. Cell (2,2)=9 is greater than all neighbors (3, 5, 2, 4) → peak. The method returns 2.
public int countPeaks(int[][] grid) {
}Main Solution
PART A — borderSum
The border of a 2D grid consists of: the first row, the last row, the first column, and the last column. Corner elements belong to two of these groups, so we must count them only once. A clean approach is to iterate over all four sides carefully, or to iterate over every cell and check whether it is on a border.
public int borderSum(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
int sum = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
if (r == 0 || r == rows - 1 || c == 0 || c == cols - 1) {
sum += grid[r][c];
}
}
}
return sum;
}Explanation:
- We loop over every cell
(r, c). - A cell is on the border if it is in the first row (
r == 0), the last row (r == rows-1), the first column (c == 0), or the last column (c == cols-1). - Corner cells satisfy two of these conditions but are added only once because the
ifcheck is evaluated once per cell. - Interior cells satisfy none of the conditions and are skipped.
Verification with the given example:
grid = {{5,3,8,1},{2,7,4,9},{6,1,3,5}}
Border cells: row 0 → 5+3+8+1=17; row 2 → 6+1+3+5=15; col 0 interior → 2; col 3 interior → 9.
Sum = 17 + 15 + 2 + 9 = 43 ✓
PART B — countPeaks
An interior cell is one that is not on any edge, i.e., row index is between 1 and rows-2 (inclusive) and column index is between 1 and cols-2 (inclusive). A peak is an interior cell strictly greater than all four direct neighbors.
public int countPeaks(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
int count = 0;
for (int r = 1; r <= rows - 2; r++) {
for (int c = 1; c <= cols - 2; c++) {
int val = grid[r][c];
if (val > grid[r - 1][c] && // up
val > grid[r + 1][c] && // down
val > grid[r][c - 1] && // left
val > grid[r][c + 1]) { // right
count++;
}
}
}
return count;
}Explanation:
- We iterate only over interior cells: rows 1 through
rows-2, columns 1 throughcols-2. - For each interior cell we compare its value to its four direct (orthogonal) neighbors.
- If it is strictly greater than all four, it is a peak and we increment
count. - We return the final count.
Verification with the given example:
grid = {{1,2,1,3},{4,8,3,1},{1,2,9,4},{2,1,5,2}}
Interior cells (rows 1–2, cols 1–2):
(1,1)=8: neighbors up=2, down=2, left=4, right=3 → 8>2, 8>2, 8>4, 8>3 → peak ✓
(1,2)=3: neighbors up=1, down=9, left=8, right=1 → 3>9 is false → not a peak
(2,1)=2: neighbors up=8, down=1, left=1, right=9 → 2>8 is false → not a peak
(2,2)=9: neighbors up=3, down=5, left=2, right=4 → 9>3, 9>5, 9>2, 9>4 → peak ✓
Count = 2 ✓
Teacher Explanation
Part A tests the ability to iterate over a 2D array and identify border elements using index boundary conditions. The key insight is that a single if with four OR-connected conditions handles corners without double-counting. Part B tests nested loops over a restricted range (interior only) and multi-condition comparisons. Students must use strict inequality (>) and check all four neighbors. Common AP scoring criteria: correct loop bounds, correct border/interior identification, correct neighbor access without ArrayIndexOutOfBoundsException, and returning the correct value.
Education Coach Advice
For 2D array FRQs on the AP exam: (1) Always use grid.length for rows and grid[0].length for columns — never hard-code sizes. (2) For border problems, the single-loop approach with an if condition is cleaner and less error-prone than four separate loops. (3) For neighbor problems, write out the four neighbor accesses explicitly and double-check row vs. column order. (4) Trace through the provided example by hand before finalizing — the exam often gives you a concrete test case you can use to verify your logic.
Traps
Part A traps:
- Double-counting corners by summing each side in a separate loop without excluding corners from the column loops.
- Off-by-one errors: using
r < rows - 1instead ofr <= rows - 1(or equivalentlyr == rows - 1), missing the last row or column. - Hard-coding dimensions instead of using
grid.lengthandgrid[0].length.
Part B traps:
- Including edge cells in the loop (starting at row/col 0 or ending at row/col
rows-1/cols-1), which causesArrayIndexOutOfBoundsExceptionwhen accessing neighbors. - Using
>=instead of>(the problem says strictly greater). - Checking only some neighbors (e.g., forgetting the down or right neighbor).
- Confusing row and column indices when accessing neighbors (e.g., writing
grid[r-1][c-1]for the up neighbor instead ofgrid[r-1][c]).
Question 160
What is printed?
int[][] grid = {{5, 2, 8, 1},
{3, 7, 4, 6},
{9, 1, 3, 2},
{4, 5, 6, 8}};
int sum = 0;
for (int i = 0; i < grid.length; i++) {
sum += grid[i][i];
sum += grid[i][grid.length - 1 - i];
}
System.out.println(sum);Main Solution
The grid is a 4×4 2D array:
| Row | Col 0 | Col 1 | Col 2 | Col 3 |
|---|---|---|---|---|
| 0 | 5 | 2 | 8 | 1 |
| 1 | 3 | 7 | 4 | 6 |
| 2 | 9 | 1 | 3 | 2 |
| 3 | 4 | 5 | 6 | 8 |
grid.length is 4. The loop runs for i = 0, 1, 2, 3. Each iteration adds grid[i][i] (main diagonal) and grid[i][grid.length - 1 - i] = grid[i][3 - i] (anti-diagonal).
| i | grid[i][i] | grid[i][3-i] | Running sum |
|---|---|---|---|
| 0 | grid[0][0] = 5 | grid[0][3] = 1 | 6 |
| 1 | grid[1][1] = 7 | grid[1][2] = 4 | 17 |
| 2 | grid[2][2] = 3 | grid[2][1] = 1 | 21 |
| 3 | grid[3][3] = 8 | grid[3][0] = 4 | 33 |
Note: When i = 1, grid[i][i] and grid[i][3-i] are different cells (col 1 vs col 2), so no double-counting issue there. When i = 0, cells are grid[0][0]=5 and grid[0][3]=1 — different. When i = 3, cells are grid[3][3]=8 and grid[3][0]=4 — different. The diagonals do not share any element in a 4×4 grid (they would only share the center in an odd-sized grid).
Total sum = 5 + 1 + 7 + 4 + 3 + 1 + 8 + 4 = 33.
The answer is A) 33.
Teacher Explanation
This question tests traversal of a 2D array along both the main diagonal (grid[i][i]) and the anti-diagonal (grid[i][grid.length - 1 - i]) simultaneously. Students must correctly evaluate both index expressions for each value of i and accumulate the sum. Since the grid is 4×4 (even dimension), the two diagonals never share a cell, so there is no double-counting.
Education Coach Advice
When you see a loop accessing grid[i][i] and grid[i][grid.length - 1 - i], trace through each value of i carefully in a table. Write out the row and column indices explicitly for each iteration — this prevents arithmetic errors with the anti-diagonal formula. Also check whether the two expressions ever point to the same cell (they do only when i == grid.length - 1 - i, i.e., in odd-sized grids at the center row).
Traps
Common traps:
- Option D (28): A student might only sum one diagonal (e.g., just the main diagonal: 5+7+3+8=23, or just the anti-diagonal: 1+4+1+4=10) or make an off-by-one error in the anti-diagonal index.
- Option B (23): This is the sum of only the main diagonal (5+7+3+8=23), forgetting that the loop also adds the anti-diagonal elements.
- Option C (30): Could result from miscalculating one of the anti-diagonal indices, e.g., using
grid.length - iinstead ofgrid.length - 1 - i, causing an ArrayIndexOutOfBoundsException or wrong values. - Students may also mistakenly think the center elements are double-counted (only relevant for odd-sized grids).
Answer images
AP® and Advanced Placement® are registered trademarks of the College Board, which is not affiliated with, and does not endorse, Verityprep. Names are used for identification purposes only.

