Question 941
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

