What to practice
- Access and modify 2D array elements and whole rows (grid[r]).
- Trace and write row-major, column-major, diagonal, and subgrid traversals.
- Write complete 2D array methods for AP CSA Free-Response Question 4.
Current CED topics: 4.11, 4.12, 4.13
Current learning objectives: 4.11.A, 4.12.A, 4.13.A
1. Core Concept Instruction
In Java, a two-dimensional array T[][] grid is an array of 1D row arrays: grid.length is the number of rows, grid[r] is the entire r-th row (a 1D array of type T[]), and grid[0].length is the number of columns in a rectangular grid. To access the element at row r, column c, always write grid[r][c] (row index first, column index second). (1) Row-Major Traversal visits elements row by row (outer loop over r from 0 to grid.length - 1; inner loop over c from 0 to grid[0].length - 1), and can also be written with nested enhanced for-each loops: for (int[] row : grid) { for (int val : row) { /* body / } }. (2) Column-Major Traversal visits elements column by column (outer loop over c from 0 to grid[0].length - 1; inner loop over r from 0 to grid.length - 1), so an explicit column index is needed. The usual pair of enhanced loops (row, then value) visits row-major. A column-major traversal can combine an indexed outer column loop with an enhanced inner row loop: for (int c = 0; c < grid[0].length; c++) { for (int[] row : grid) { / use row[c] */ } }. This example assumes a nonempty rectangular grid. For {{1, 2, 3}, {4, 5, 6}}, it visits 1, 4, 2, 5, 3, 6.
2. Worked Examples
Computing Column Sums in a Rectangular Array
Given int[][] mat = {{2, 5, 1}, {4, 0, 8}}; (2 rows, 3 columns), trace the array colSums returned by:
int[] colSums = new int[mat[0].length];
for (int c = 0; c < mat[0].length; c++) {
int sum = 0;
for (int r = 0; r < mat.length; r++) {
sum += mat[r][c];
}
colSums[c] = sum;
}
- Step 1 (Check Dimensions): mat.length is 2 (rows 0..1) and mat[0].length is 3 (columns 0..2), so colSums has length 3.
- Step 2 (Column c = 0): r = 0..1 sums mat[0][0] + mat[1][0] = 2 + 4 = 6 -> colSums[0] = 6.
- Step 3 (Column c = 1): r = 0..1 sums mat[0][1] + mat[1][1] = 5 + 0 = 5 -> colSums[1] = 5.
- Step 4 (Column c = 2): r = 0..1 sums mat[0][2] + mat[1][2] = 1 + 8 = 9 -> colSums[2] = 9. Final array: {6, 5, 9}.
Result:
2D Array Main-Diagonal vs. Anti-Diagonal Accumulation Trace
Given int[][] grid = {{2, 5, 9}, {4, 7, 1}, {8, 3, 6}}, trace:
int mainDiag = 0, antiDiag = 0;
for (int i = 0; i < grid.length; i++) {
mainDiag += grid[i][i];
antiDiag += grid[i][grid.length - 1 - i];
}
- Step 1 (Sum main diagonal grid[i][i]): 2 + 7 + 6 = 15.
- Step 2 (Sum anti-diagonal grid[i][2 - i]): grid[0][2] (9) + grid[1][1] (7) + grid[2][0] (8) = 24.
Result: mainDiag = 15 and antiDiag = 24