AP® Computer Science A · Unit 4 · Topic 4.12

Row-Major Traversal with Nested Loops

Row-major traversal visits a 2D array one full row at a time, using an outer loop for the row index and an inner loop that sweeps across every column before moving to the next row.

A 2D array is really an array of arrays: each row is itself an array of values. To visit every element exactly once, you need two counters. The outer loop variable, often called row or i, picks which row you're in. The inner loop variable, often col or j, then runs all the way across that row before the outer loop moves on. That's why the outer loop owns rows and the inner owns columns: the inner loop has to finish a full pass before the outer loop takes its next step, matching how row-major order lists row 0 completely, then row 1 completely, and so on.

Mechanically, for a grid named grid with r rows and c columns, the outer loop runs i from 0 to r-1. Inside it, the inner loop runs j from 0 to c-1, and the body reads or updates grid[i][j]. Each pairing of i and j happens exactly once, so the total number of visits is r times c. This is the same pattern used to sum, search, or print every cell: the loops don't change, only what you do with grid[i][j] inside them changes.

An enhanced for loop can replace the index-based loops when you only need the values, not their positions. The outer enhanced for pulls out each row, which is itself a 1D array, and the inner enhanced for pulls out each element of that row. You lose direct access to i and j, so this version is cleaner for tasks like summing all elements but useless for tasks that need coordinates, like finding where a value sits or comparing neighbors. Row-major traversal is the foundation for the searches and sorts on grids that follow, since they all rely on visiting cells in a predictable, complete order.

Key terms

Row-major order
A traversal that visits every element of row 0, then every element of row 1, and so on.
Outer loop
The loop that controls the row index and advances once per full inner loop pass.
Inner loop
The loop that controls the column index and completes a full sweep across one row before the outer loop advances.
2D array
An array whose elements are themselves arrays, commonly visualized as a grid of rows and columns.
Enhanced for loop
A for-each loop that retrieves each value in sequence without exposing its index.

Watch it explained

  1. How it worksHow do two nested counters sweep every cell of a grid exactly once?
  2. Worked exampleTrace the visiting order of a 3 by 4 grid under row-major traversal.
  3. Worked exampleFind the sum of every element in { {2,4}, {6,8}, {1,3} } using nested loops.
  4. Going furtherWhat changes when an enhanced for loop is nested to walk a 2D array?

Check yourself

Your turn1 of 2
Under row-major traversal, a nested loop visits every cell of a grid with 15 rows and 14 columns exactly once. How many cells does it visit in total?

End of topic.