2D Array Traversals
| English | Chinese | Pinyin |
|---|---|---|
| nested loops | 嵌套循环 | qiàn tào xún huán |
| row-major order | 行主序 | xíng zhǔ xù |
| enhanced for | 增强循环 | zēng qiáng xún huán |
Nested loops for a grid
- To visit every cell of a 2-D array, use nested loops 嵌套循环 (from Unit 2).
- Outer loop over rows, inner loop over columns:
for (int r = 0; r < g.length; r++) { for (int c = 0; c < g[0].length; c++) { ... g[r][c] ... } }- The inner loop sweeps a full row before the outer moves to the next.
Row-major order
- This nesting visits cells in row-major order 行主序: all of row 0, then row 1, …
g[0][0], g[0][1], …, g[1][0], g[1][1], …- It's the natural reading order — left to right, top to bottom.
- Swap the loops (columns outer) to go column-major instead.
The for-each version
- An enhanced for 增强循环 loop over a 2-D array gives one row (a 1-D array) at a time.
for (int[] row : g) { for (int x : row) { ... x ... } }- The outer variable is a whole row; the inner walks that row's values.
- Clean for reading; can't modify cells or use indices.
Bounding correctly
- Outer bound:
r < g.length(rows). Inner bound:c < g[0].length(columns). - Using the wrong length for a loop is a subtle bug in non-square grids.
- For a rectangular grid,
g[0].lengthgives the column count for every row. - The inner body runs
rows × columnstimes total.
Bound the outer loop with g.length (rows) and the inner with g[0].length (columns) — not the same value unless the grid is square. Swapping them, or reusing one length for both loops, walks past the edge of a non-square grid and throws an exception. The total number of cells visited is rows × columns.
Summing a 2-D array:
for (int r = 0; r < g.length; r++)for (int c = 0; c < g[0].length; c++)sum += g[r][c];— visits allrows × colscells, row by row.
Traverse a 2-D array with nested loops: outer over rows (r < g.length), inner over columns (c < g[0].length), accessing g[r][c]. This visits cells in row-major order (rows × columns total). An enhanced for (for (int[] row : g)) hands one row at a time for read-only traversal.
Row-major traversal
Outer loop over rows, inner over columns: 1,2,3,4,5,6.
To visit every cell of a 2-D array, you use...
Outer over rows, inner over columns.
The outer loop of a 2-D traversal should be bounded by...
Outer = rows = g.length; inner = columns = g[0].length.
For a 2-row, 3-column grid, how many cells does the nested loop visit?
rows × columns = 2 × 3 = 6.
Row-major traversal visits cells in the order...
Row-major = left to right, top to bottom.
In for (int[] row : g), the variable row is...
The outer for-each variable is a row array.