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.
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-major | Column-major | |
|---|---|---|
| Outer loop | for (int r = 0; r < arr.length; r++) | for (int c = 0; c < arr[0].length; c++) |
| Inner loop | for (int c = 0; c < arr[0].length; c++) | for (int r = 0; r < arr.length; r++) |
| Element | arr[r][c] | arr[r][c] |
| Order for { {1, 2, 3}, {4, 5, 6} } | 1 2 3 4 5 6 | 1 4 2 5 3 6 |
| Enhanced for version? | Yes: rows, then elements | No: 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.
Printing a Grid Row by Row
Predict the output.
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));
}
1 2 3
4 5 6
- 1Outer loop: rows.
rruns whiler < g.length, the number of rows (2). - 2Inner loop: columns.
cruns whilec < g[0].length, the number of columns (3). - 3One line per row. The inner loop builds a row's text;
substring(1)drops the leading space.
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.
| c (outer) | r (inner) | Element visited | Value |
|---|---|---|---|
| 0 | 0 | g[0][0] | 1 |
| 0 | 1 | g[1][0] | 4 |
| 1 | 0 | g[0][1] | 2 |
| 1 | 1 | g[1][1] | 5 |
| 2 | 0 | g[0][2] | 3 |
| 2 | 1 | g[1][2] | 6 |
Visiting Down Each Column
Predict the output.
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));
1 4 2 5 3 6
- 1Outer loop: columns.
cstays fixed while the inner loop moves down. - 2Inner loop: rows. For
c = 0it visitsg[0][0]theng[1][0]: 1, 4. - 3The element expression is still
g[r][c]: row first, column second, whatever the loop order.
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].
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 variable | Type | What it holds | Assigning to it |
|---|---|---|---|
Outer: row | int[] (a 1D array) | A reference to each row in turn | Does not change the 2D array |
Inner: v | int (the element type) | A copy of each element's value | Does not change the array |
Summing Every Element
Predict the output.
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);
21 3
- 1Outer variable
rowhas typeint[]: it is each row in turn. - 2Inner variable
vhas typeint: each element of the current row. - 3Results. 1 + 2 + 3 + 4 + 5 + 6 = 21, and three values (4, 5, 6) are greater than 3.
for loops read every element in row-major order without any index variables.Assigning to v Changes Nothing
The goal is to set every element to 0. Predict the output.
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]);
1 6
0 0
- 1
v = 0;changes only the loop variable, a copy of the element's value. The array is untouched: 1 6. - 2Indexed loops assign through
g[r][c], which changes the stored elements: 0 0.
for loop variable does not change the value stored in the array; use indexed loops to modify elements.The Outer Variable Is Not an int
Explain the compile error.
int[][] g = { {1, 2, 3}, {4, 5, 6} };
for (int row : g)
{
System.out.println(row);
}
- 1The elements of
gare rows, each anint[]. - 2The outer loop variable must therefore be declared
int[] row; anintcannot hold a whole row.
for loop, the outer variable must be the type of each row, a 1D array.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.
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.
Summing a Single Row and Column
Predict the output.
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);
15 7
- 1Row 1 is the 1D array
g[1], so a plain enhanced for loop reads it: 4 + 5 + 6 = 15. - 2Column 1 has no array of its own; fix the column index at 1 and vary the row: 2 + 5 = 7.
Snaking Back and Forth
Even rows go left to right; odd rows go right to left. Predict the output.
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));
1 2 3 6 5 4 7 8 9
- 1Row 0 runs forward: 1 2 3.
- 2Row 1 runs backward from the last column: 6 5 4.
- 3Row 2 runs forward again: 7 8 9.
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.
Mixing Up the Two Lengths
The intent is a row-major traversal. What happens?
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);
- 1The row loop uses the column count, 3, so
rreaches 2, butghas only rows 0 and 1. - 2
g[2][0]throws anArrayIndexOutOfBoundsException. - 3Match each bound to its index:
r < g.length,c < g[0].length.
ArrayIndexOutOfBoundsException. The row index is bounded by arr.length and the column index by arr[0].length.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.
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.