TOPIC 4.12 · STUDY
2D Array Traversals
A 2D array traversal visits every element with nested loops. Row-major order finishes each row before the next; column-major order finishes each column before the next. The outer loop chooses which order you get.
4.12.A
2D Array Traversals
Traversing a 2D array means visiting its elements in a planned order with nested loops. Row-major order walks one full row at a time: for each row, visit every column in that row, then move to the next row. Column-major order walks one full column at a time: for each column, visit every row in that column, then move to the next column.
The outer loop decides the order. When the outer loop steps through rows and the inner loop steps through columns, you get row-major. When the outer loop steps through columns and the inner loop steps through rows, you get column-major. Swap which index the outer loop controls, and the visit order flips.
The standard nested pair for row-major uses an outer row index r from 0 to grid.length - 1 and an inner column index c from 0 to grid[r].length - 1. That pattern finishes row 0 before row 1 begins.
int[][] seats = { {7, 2}, {5, 9} };
for (int r = 0; r < seats.length; r++) {
for (int c = 0; c < seats[r].length; c++) {
System.out.print(seats[r][c]);
}
}
// Visit order: [0][0], [0][1], [1][0], [1][1]. Output: 7259
When every row has the same length, swapping the loops gives column-major. The outer loop runs across columns, and the inner loop runs down the rows of the current column. Use seats[0].length (or any row's length) for the column bound only when the grid is rectangular.
int[][] seats = { {7, 2}, {5, 9} };
for (int c = 0; c < seats[0].length; c++) {
for (int r = 0; r < seats.length; r++) {
System.out.print(seats[r][c]);
}
}
// Visit order: [0][0], [1][0], [0][1], [1][1]. Output: 7529
Row-major visit order: cell 1 then cell 2 finish the first row; cell 3 starts the next row.
Key points
- Row-major order visits every column in a row before moving to the next row.
- Column-major order visits every row in a column before moving to the next column.
- The outer loop chooses whether you finish a row first or a column first.
- Outer r from 0 to grid.length - 1 and inner c from 0 to grid[r].length - 1 is row-major.
- Swapping those loops on a rectangular grid is column-major.
The outer loop decides whether you finish a row or a column first.