AP Computer Science A · Study guide

2D Array Traversals

AP® Computer Science A · Data Collections

2D Array Traversals

Visiting every element of a 2D array with nested loops: row-major and column-major order, nested enhanced for loops and the types of their variables, single rows and columns, uniquely defined orders, and the bound mistakes to avoid.

Big Picture

Nested iteration statements are used to traverse and access all or an ordered sequence of elements in a 2D array. Because 2D arrays are stored as arrays of arrays, they are traversed with for loops and enhanced for loops much like 1D arrays. Row-major order traverses across each row; column-major order traverses down each column; a traversal can also follow any uniquely defined order. In a nested enhanced for loop, the outer variable is a row, a 1D array, and the inner variable has the element type; assigning to either variable does not change the array.

1Nested Loops Visit Every Element

A single loop visits the elements of a 1D array. A 2D array has two indices, so visiting every element takes two loops, one inside the other: one loop chooses a row or column, and the other moves through the elements along it. For every pass of the outer loop, the inner loop runs completely, so a grid with 3 rows and 4 columns produces 3 × 4 = 12 visits.

Whatever the order, the element itself is always written arr[r][c], row first and column second. What changes between traversals is which index the outer loop controls. Keeping the bounds straight is the key skill: the row index is limited by arr.length, the number of rows, and the column index by arr[0].length, the number of columns.

Row-majorColumn-major
Outer loopfor (int r = 0; r < arr.length; r++)for (int c = 0; c < arr[0].length; c++)
Inner loopfor (int c = 0; c < arr[0].length; c++)for (int r = 0; r < arr.length; r++)
Elementarr[r][c]arr[r][c]
Order for { {1, 2, 3}, {4, 5, 6} }1 2 3 4 5 61 4 2 5 3 6
Enhanced for version?Yes: rows, then elementsNo: needs indices

2Row-Major Order

Row-major order refers to an ordering of 2D array elements where traversal occurs across each row. The outer loop runs through the rows, and for each row the inner loop runs through every column. The elements of row 0 are all visited first, then those of row 1, and so on, which is the same order in which people read a page.

Row-major order is the natural choice for printing a grid one line per row, for processing data stored by record, and for any task that does not depend on order, such as computing a total. It is also the order a nested enhanced for loop follows.

Figure 1. Row-major order traverses across each row: the outer loop chooses the row and the inner loop moves through its columns.
Worked Example 1 Row-major

Printing a Grid Row by Row

Predict the output.

Code
int[][] g = { {1, 2, 3}, {4, 5, 6} };

for (int r = 0; r < g.length; r++)
{
    String line = "";
    for (int c = 0; c < g[0].length; c++)
    {
        line += " " + g[r][c];
    }
    System.out.println(line.substring(1));
}
Output
1 2 3
4 5 6
  1. 1Outer loop: rows. r runs while r < g.length, the number of rows (2).
  2. 2Inner loop: columns. c runs while c < g[0].length, the number of columns (3).
  3. 3One line per row. The inner loop builds a row's text; substring(1) drops the leading space.
Result: The output is 1 2 3 on the first line and 4 5 6 on the second. Row-major order visits every element of a row before moving to the next row.
Common Mistake 1 · Using arr.length for the Columns

The inner loop of a row-major traversal must use arr[0].length. Writing c < arr.length limits the columns by the number of rows, which either skips columns or runs past the end of each row.

3Column-Major Order

Column-major order traversal occurs down each column. The outer loop runs through the columns, and for each column the inner loop runs through every row. The element expression is still arr[r][c]; only the nesting of the loops changes, along with the bounds that go with each index.

Column-major order is needed when a task is organized by column: totals for each column of a table, checking whether a column is in order, or printing a grid sideways. Because each row is a separate array, there is no single array for a column, so column-major traversals always use index loops.

Figure 2. Column-major order traverses down each column: the outer loop chooses the column and the inner loop moves through the rows.
c (outer)r (inner)Element visitedValue
00g[0][0]1
01g[1][0]4
10g[0][1]2
11g[1][1]5
20g[0][2]3
21g[1][2]6
Worked Example 2 Column-major

Visiting Down Each Column

Predict the output.

Code
int[][] g = { {1, 2, 3}, {4, 5, 6} };

String order = "";
for (int c = 0; c < g[0].length; c++)
{
    for (int r = 0; r < g.length; r++)
    {
        order += " " + g[r][c];
    }
}
System.out.println(order.substring(1));
Output
1 4 2 5 3 6
  1. 1Outer loop: columns. c stays fixed while the inner loop moves down.
  2. 2Inner loop: rows. For c = 0 it visits g[0][0] then g[1][0]: 1, 4.
  3. 3The element expression is still g[r][c]: row first, column second, whatever the loop order.
Result: The output is 1 4 2 5 3 6. Column-major order visits every element of a column before moving to the next column.

4Nested Enhanced for Loops

The outer loop of a nested enhanced for loop used to traverse a 2D array traverses the rows. Therefore, the enhanced for loop variable must be the type of each row, which is a 1D array, such as int[] row. The inner loop traverses a single row, so the inner loop variable must be the same type as the elements stored in the 1D array, such as int v.

Assigning a new value to the enhanced for loop variable does not change the value stored in the array. The inner variable holds a copy of each element's value, so nested enhanced for loops are for reading: sums, counts, searches, and maximums. To modify elements, use indexed loops and assign through arr[r][c].

Figure 3. In a nested enhanced for loop, the outer variable has the type of a row, a 1D array, and the inner variable has the type of the elements.
Loop variableTypeWhat it holdsAssigning to it
Outer: rowint[] (a 1D array)A reference to each row in turnDoes not change the 2D array
Inner: vint (the element type)A copy of each element's valueDoes not change the array
Worked Example 3 Nested enhanced for

Summing Every Element

Predict the output.

Code
int[][] g = { {1, 2, 3}, {4, 5, 6} };

int total = 0;
int big = 0;
for (int[] row : g)
{
    for (int v : row)
    {
        total += v;
        if (v > 3)
        {
            big++;
        }
    }
}
System.out.println(total + " " + big);
Output
21 3
  1. 1Outer variable row has type int[]: it is each row in turn.
  2. 2Inner variable v has type int: each element of the current row.
  3. 3Results. 1 + 2 + 3 + 4 + 5 + 6 = 21, and three values (4, 5, 6) are greater than 3.
Result: The output is 21 3. Nested enhanced for loops read every element in row-major order without any index variables.
Worked Example 4 Loop variables are copies

Assigning to v Changes Nothing

The goal is to set every element to 0. Predict the output.

Code
int[][] g = { {1, 2, 3}, {4, 5, 6} };

for (int[] row : g)
{
    for (int v : row)
    {
        v = 0;
    }
}
System.out.println(g[0][0] + " " + g[1][2]);
for (int r = 0; r < g.length; r++)
{
    for (int c = 0; c < g[0].length; c++)
    {
        g[r][c] = 0;
    }
}
System.out.println(g[0][0] + " " + g[1][2]);
Output
1 6
0 0
  1. 1v = 0; changes only the loop variable, a copy of the element's value. The array is untouched: 1 6.
  2. 2Indexed loops assign through g[r][c], which changes the stored elements: 0 0.
Result: The output is 1 6, then 0 0. Assigning a new value to the enhanced for loop variable does not change the value stored in the array; use indexed loops to modify elements.
Worked Example 5 Enhanced for types

The Outer Variable Is Not an int

Explain the compile error.

Code that does not compile
int[][] g = { {1, 2, 3}, {4, 5, 6} };

for (int row : g)
{
    System.out.println(row);
}
  1. 1The elements of g are rows, each an int[].
  2. 2The outer loop variable must therefore be declared int[] row; an int cannot hold a whole row.
Result: The code does not compile. In a nested enhanced for loop, the outer variable must be the type of each row, a 1D array.
Common Mistake 2 · Declaring the Outer Variable With the Element Type

for (int row : g) does not compile, because the elements of a 2D array are rows of type int[]. Declare the outer variable as a 1D array and the inner variable as the element type.

Common Mistake 3 · Modifying Elements Through Enhanced for Variables

v = 0; inside a nested enhanced for loop changes only the copy. The array keeps its old values. Use arr[r][c] = 0; in indexed loops instead.

5Single Rows, Single Columns, and Other Orders

Not every task needs the whole grid. To traverse one row, fix the row index and loop over the columns; because a row is itself a 1D array, an enhanced for loop over arr[r] works too. To traverse one column, fix the column index and loop over the rows, reading arr[r][c] each time.

Nested iteration statements can also traverse a 2D array in a uniquely defined order. Traversing from the last row upward, reading each row backward, or snaking back and forth across alternating rows are all possible: each is a choice of where each loop starts, where it stops, and which way it counts. Tracing a small grid by hand confirms that every element is visited exactly once.

Figure 4. A traversal of one row fixes the row index and varies the column; a traversal of one column fixes the column index and varies the row.
Worked Example 6 One row, one column

Summing a Single Row and Column

Predict the output.

Code
int[][] g = { {1, 2, 3}, {4, 5, 6} };

int rowSum = 0;
for (int v : g[1])
{
    rowSum += v;
}
int colSum = 0;
for (int r = 0; r < g.length; r++)
{
    colSum += g[r][1];
}
System.out.println(rowSum + " " + colSum);
Output
15 7
  1. 1Row 1 is the 1D array g[1], so a plain enhanced for loop reads it: 4 + 5 + 6 = 15.
  2. 2Column 1 has no array of its own; fix the column index at 1 and vary the row: 2 + 5 = 7.
Result: The output is 15 7. Traversing one row or one column needs only a single loop (Figure 4).
Worked Example 7 A uniquely defined order

Snaking Back and Forth

Even rows go left to right; odd rows go right to left. Predict the output.

Code
int[][] g = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
String order = "";
for (int r = 0; r < g.length; r++)
{
    if (r % 2 == 0)
    {
        for (int c = 0; c < g[0].length; c++)
        {
            order += " " + g[r][c];
        }
    }
    else
    {
        for (int c = g[0].length - 1; c >= 0; c--)
        {
            order += " " + g[r][c];
        }
    }
}
System.out.println(order.substring(1));
Output
1 2 3 6 5 4 7 8 9
  1. 1Row 0 runs forward: 1 2 3.
  2. 2Row 1 runs backward from the last column: 6 5 4.
  3. 3Row 2 runs forward again: 7 8 9.
Result: The output is 1 2 3 6 5 4 7 8 9. Nested loops can traverse a 2D array in row-major order, column-major order, or any uniquely defined order.

6Bound Mistakes

Most 2D traversal errors come from pairing an index with the wrong length. If the row index is bounded by the number of columns, or the column index by the number of rows, the code works only for square arrays and fails with an ArrayIndexOutOfBoundsException otherwise. A grid that has a different number of rows and columns exposes the mistake immediately, so test with one.

A second family of errors comes from using <= instead of <, which makes a loop run one index past the end. The fix is the same as for 1D arrays: indices run from 0 to the length minus 1.

Worked Example 8 Swapped bounds

Mixing Up the Two Lengths

The intent is a row-major traversal. What happens?

Code
int[][] g = { {1, 2, 3}, {4, 5, 6} };

int total = 0;
for (int r = 0; r < g[0].length; r++)
{
    for (int c = 0; c < g.length; c++)
    {
        total += g[r][c];
    }
}
System.out.println(total);
  1. 1The row loop uses the column count, 3, so r reaches 2, but g has only rows 0 and 1.
  2. 2g[2][0] throws an ArrayIndexOutOfBoundsException.
  3. 3Match each bound to its index: r < g.length, c < g[0].length.
Result: The program stops with an ArrayIndexOutOfBoundsException. The row index is bounded by arr.length and the column index by arr[0].length.
Common Mistake 4 · Testing Only With Square Grids

When a grid has as many rows as columns, swapped bounds still work, hiding the bug. Use a grid such as 2 rows by 3 columns when tracing or testing a traversal, so that each length is distinct.

Four Habits for 2D Traversals

1. Pair Index With Length

r < arr.length; c < arr[0].length.

2. Choose the Order

Outer rows for row-major; outer columns for column-major.

3. Enhanced for Reads

int[] row, then int v; indexes to modify.

4. Test a Non-Square Grid

It exposes swapped bounds.

Core Synthesis

Nested iteration statements are used to traverse and access all or an ordered sequence of elements in a 2D array. Since 2D arrays are stored as arrays of arrays, the way 2D arrays are traversed using for loops and enhanced for loops is similar to 1D array objects. Nested iteration statements can traverse a 2D array in row-major order, column-major order, or a uniquely defined order; row-major order traverses across each row, and column-major order traverses down each column. The outer loop of a nested enhanced for loop traverses the rows, so its variable must be the type of each row, a 1D array; the inner loop traverses a single row, so its variable must be the same type as the elements. Assigning a new value to an enhanced for loop variable does not change the value stored in the array.