Lesson 12: Two-Dimensional Arrays — Rows, Columns and Traversals
A two-dimensional array is an array of arrays, and it is the natural way to store a grid: a seating chart, a game board, a table of values, or the pixels of an image. You declare it as int[][] grid = new int[3][4];, which creates three rows of four columns, and you reach an element with two indices, grid[row][col], where the row comes first. The number of rows is grid.length, and the number of columns in a row is grid[row].length, and those two expressions are the bounds for the nested loops that traverse the grid.
Traversing a two-dimensional array means visiting every element, and the standard pattern is a pair of nested loops: the outer loop runs over the rows, and the inner loop runs over the columns of the current row. This is called row-major order, and it visits the elements row by row, from the top-left corner to the bottom-right. The inner loop's bound should be grid[row].length, not a fixed number, because Java allows ragged arrays, where different rows have different lengths. Column-major order, which visits column by column, is also possible, but row-major is the default and the one exam questions usually expect.
Many algorithms on two-dimensional arrays are the one-dimensional patterns applied twice over. Summing all elements means accumulating over every row and column; finding the largest value means comparing across the whole grid; counting elements that satisfy a condition means filtering in two dimensions. Other algorithms use the grid's structure: summing a single row means fixing the row index and looping over columns, summing a single column means fixing the column and looping over rows, and finding a value means searching row by row and returning its position. When you write such a method, decide first which indices are fixed and which vary.
Two-dimensional arrays are also a favourite source of exam errors, because there are two indices to confuse and two lengths to mix up. The commonest mistake is swapping the row and column, writing grid[col][row] instead of grid[row][col], which compiles happily and produces wrong answers or an exception. Another is using grid.length where grid[0].length is needed, or assuming all rows have the same length. A sketch of the grid with its indices labelled is the best defence: draw the rows and columns, mark the element you want, and read off the two indices in order.
A two-dimensional array is passed to a method exactly like a one-dimensional array: the parameter is declared as int[][], and the method receives a reference to the caller's grid, so changes to elements inside the method are visible to the caller. The enhanced for loop can also traverse a grid, with an outer loop over the rows and an inner loop over the values in each row, as in for (int[] row : grid) { for (int value : row) { ... } }, which is the clearest form when you only need the values. But the enhanced form cannot tell you the row or column of an element, so any method that must report a position, such as finding where the largest value sits, needs the indexed loops instead. Choose the form that gives you the information the task requires.
A worked example
Worked example: the method below returns the sum of all elements in a two-dimensional array. The outer loop runs over the rows and the inner loop over the columns of each row, accumulating every element into a running total.
public int sumAll(int[][] grid)
{
int total = 0;
for (int row = 0; row < grid.length; row++)
{
for (int col = 0; col < grid[row].length; col++)
{
total += grid[row][col];
}
}
return total;
}
// sumAll({{1, 2}, {3, 4, 5}}) returns 15
The grid has two rows: the first has two elements and the second has three, a ragged array, and the inner bound grid[row].length handles each row's own length correctly. The total accumulates 1 + 2 + 3 + 4 + 5 = 15. If the inner bound had been grid[0].length, the second row's third element would have been skipped; if it had been grid.length, the first row would have been read past its end. Use the row's own length, and ragged arrays work without special cases.
A 3-row by 4-column grid
The row index comes first: grid[1][2] is row 1, column 2. Row-major traversal visits row 0 fully, then row 1, then row 2.
Key Terms
- Two-dimensional array
- An array of arrays, accessed as grid[row][col], used for grids and tables.
- Row-major order
- Traversing a grid row by row, with the outer loop over rows and the inner loop over columns.
- Ragged array
- A two-dimensional array whose rows have different lengths.
- grid.length
- The number of rows in a two-dimensional array.
- grid[row].length
- The number of columns in row row of a two-dimensional array.
Discussion Questions
- Why is the row index written first in grid[row][col]?
- What goes wrong if you use grid.length as the bound for the inner loop?
- How would you sum a single column of a grid?
Practice Questions
- int[][] g = new int[4][3]; How many rows and columns does g have?
- What does g.length give, and what does g[0].length give?
- Write the nested loop headers to visit every element of int[][] grid in row-major order.
- What is the last valid index pair for a 3-row, 5-column grid?
- Why should the inner loop bound be grid[row].length rather than grid[0].length?
Show answers
- 4 rows and 3 columns.
- g.length is 4, the number of rows; g[0].length is 3, the number of columns in row 0.
- for (int row = 0; row < grid.length; row++) { for (int col = 0; col < grid[row].length; col++) { ... } }
- [2][4].
- Because rows may have different lengths in a ragged array, and each row's own length is the correct bound.