AP Computer Science A · Topic 8.2
Traversing 2D Arrays Practice
Part of 2D Array.
Practice questions
36
Sample questions
5 of 36 — sign in to practice the rest with adaptive difficulty and mastery tracking.
Sample 1difficulty 2/5
int[][] m = {{2, 3}, {4, 5}}; int product = 1; for (int[] row : m) { for (int x : row) { product *= x; } } System.out.println(product);What is printed?
- Acheck_circle
120
- B
60
- C
100
- D
14
Why
2 * 3 * 4 * 5 = 120.
- A
Sample 2difficulty 3/5
public static int run() { int[][] m = {{1,2,3},{4,5,6}}; int s = 0; for (int[] row : m) { for (int v : row) { if (v % 2 == 1) s += v; } } return s; } // Call: System.out.println(run());What is printed?
- A
12
- B
21
- C
6
- Dcheck_circle
9
Why
Odd values: 1, 3, 5. Sum = 9.
- A
Sample 3difficulty 3/5
public static int run() { int[][] g = new int[3][3]; for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) g[i][j] = i * 3 + j; g[1][1] = g[0][2] + g[2][0]; return g[1][1]; } // Call: System.out.println(run());What is printed?
- A
4
- Bcheck_circle
8
- C
10
- D
6
Why
g[0][2] = 0<em>3+2 = 2. g[2][0] = 2</em>3+0 = 6. g[1][1] = 2 + 6 = 8.
- A
Sample 4difficulty 3/5
for (int r = 0; r <= grid.length; r++) { for (int c = 0; c < grid[0].length; c++) { grid[r][c] = 0; } }Which fix corrects the bounds error?
- Acheck_circle
Change r <= grid.length to r < grid.length
- B
Swap rows and columns
- C
Use grid[r-1][c]
- D
Change c < grid[0].length to c <= grid[0].length
Why
Row indices run 0 to grid.length-1. The outer condition must be r < grid.length to avoid an out-of-bounds access.
- A
Sample 5difficulty 3/5
public static int sum2D(int[][] g) { int total = 0; for (int r = 0; r < g.length; r++) { for (int c = 0; c < /* missing */; c++) { total += g[r][c]; } } return total; }Which expression replaces /* missing */ assuming each row may differ in length?
- A
g[c].length
- B
g[0].length
- C
g.length
- Dcheck_circle
g[r].length
Why
For ragged arrays, use the length of the current row g[r].length. g[0].length only works for rectangular grids.
- A