AP® Computer Science A · Unit 4 · Topic 4.12
Column-Major Traversal and Diagonals
Column-major traversal visits a 2D array column by column by putting the column loop on the outside, while a diagonal uses one counter for both row and column index.
Normal row-major traversal uses an outer loop over rows and an inner loop over columns, so you finish an entire row before moving to the next. Column-major traversal just swaps which loop sits outside: the outer loop fixes a column, and the inner loop walks down the rows of that column before moving to the next column. The code pattern barely changes — you still write grid[row][col] — but now row is the inner variable that changes fast, and col is the outer variable that changes slow. That swap is the whole trick: the loop nesting controls the order of visits, not the array itself.
On a non-square grid the bounds have to swap too, not just the loop order. A 3 by 5 grid has 3 rows and 5 columns. Row-major loops outer over rows (0 to 2) and inner over columns (0 to 4). Column-major must loop outer over columns (0 to 4) and inner over rows (0 to 2) — the outer bound becomes the column count, the inner bound becomes the row count. Copying row-major's bounds unchanged is a common setup that throws an ArrayIndexOutOfBoundsException on anything but a square grid.
Diagonals are a special case that needs no nested loop at all. The main diagonal of a square grid always has equal row and column index, so a single loop with one counter i walks grid[i][i] from i = 0 up to the last row. This connects column-major and diagonal traversal back to the bigger idea of the unit: once you're comfortable treating the loop structure itself as something you design, you can visit a grid's cells in whatever order a problem needs — rows, columns, diagonals, or something else entirely.
Key terms
- Row-major traversal
- Visiting a 2D array by finishing each row, outer loop over rows and inner loop over columns.
- Column-major traversal
- Visiting a 2D array by finishing each column, outer loop over columns and inner loop over rows.
- Main diagonal
- The cells of a square grid where the row index equals the column index, grid[i][i].
- Loop bounds
- The starting and ending values that control how many times a loop runs, tied to row or column count.
Watch it explained
- How it worksHow does putting the column loop outside walk down each column instead of across?
- Worked exampleTrace column-major order on a 3 by 3 grid and list the cells in the order they are hit.
- Worked exampleFind the main diagonal of a 4 by 4 grid using a single loop with one counter.
- Common mistakeWhy doesn't column-major traversal keep the same bounds as row-major on a non-square grid?
Check yourself
End of topic.