impera Open Impera

AP Computer Science A · Data collections

2D arrays

1Creating 2D arrays

A 2D array is an array of arrays, used for grids and tables. It is accessed by [row][column]:

int[][] grid = new int[3][4];     // 3 rows, 4 columns, all 0
int[][] m = { {1, 2, 3}, {4, 5, 6} };
  • m.length is the number of rows (2).
  • m[0].length is the number of columns (3).
  • m[1][2] is 6 (row 1, column 2).

In AP CSA, 2D arrays are rectangular (every row has the same length) and are thought of in row-major order.

A 2D array is indexed [row][column]

Check yourself

For int[][] t = new int[5][2];, t[0].length is:

  • 5

  • 2

  • 10

  • 0

Show the answer

2

Columns.

2Row-major traversal

Visit each row in turn, and every column within it:

for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[0].length; c++) {
        System.out.print(grid[r][c] + " ");
    }
    System.out.println();
}

With enhanced for loops:

for (int[] row : grid) {
    for (int value : row) {
        sum += value;
    }
}

The outer for-each variable is a whole row (a 1D array).

Check yourself

In for (int[] row : grid), what type is row?

  • Integer

  • int[] (one row)

  • int

  • int[][]

Show the answer

int[] (one row)

Each element of grid is a row.

3Column-major and other traversals

Column-major: swap the loops so the outer loop runs over columns:

for (int c = 0; c < grid[0].length; c++) {
    for (int r = 0; r < grid.length; r++) {
        // grid[r][c]
    }
}

Other patterns:

  • Row sums: reset the sum inside the outer loop.
  • One column: fix c, loop over r.
  • Main diagonal of a square grid: grid[i][i].
  • Neighbours: check r - 1, r + 1, c - 1, c + 1 stay within bounds before accessing.
Worked example

for m = { {1, 2, 3}, {4, 5, 6} }, column-major order visits 1, 4, 2, 5, 3, 6.

Check yourself

Which visits a 2D array column by column?

  • for (int x : grid)

  • Outer loop over columns, inner over rows

  • A single loop over grid.length

  • Outer loop over rows, inner over columns

Show the answer

Outer loop over columns, inner over rows

Column-major.

4Bounds and common errors

  • grid.length and grid[0].length are easily swapped: rows first, then columns.
  • Indexing grid[r][c] with r up to grid[0].length fails when the grid is not square.
  • Neighbour checks need conditions like r > 0 before grid[r - 1][c].
Check yourself

A 3 × 5 grid uses r < 5 and c < 3 in its loops. What happens?

  • It visits each element twice

  • A compile-time error

  • It works for all elements

  • ArrayIndexOutOfBoundsException

Show the answer

ArrayIndexOutOfBoundsException

Rows and columns swapped.

5Going deeper: rows of arrays, standard traversals and neighbors

A 2D array is an array of arrays. int[][] grid = new int[3][4]; creates 3 rows and 4 columns.

  • grid.length is the number of rows.
  • grid[0].length is the number of columns.
  • grid[r][c]: row first, then column.
  • grid[r] is itself a 1D array (a whole row) and can be passed to any method that takes a 1D array.

With an initializer: int[][] m = { {1, 2, 3}, {4, 5, 6} }; has 2 rows and 3 columns; m[1][0] is 4.

Row-major traversal (row by row): outer loop over rows.

for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[0].length; c++) {
        System.out.print(grid[r][c] + " ");
    }
    System.out.println();
}

Column-major traversal (column by column): outer loop over columns.

for (int c = 0; c < grid[0].length; c++) {
    for (int r = 0; r < grid.length; r++) {
        System.out.print(grid[r][c] + " ");
    }
}

The index order inside the brackets stays [r][c]; only the nesting of the loops changes.

Enhanced for loops: the outer variable is a row (a 1D array).

for (int[] row : grid) {
    for (int value : row) {
        sum += value;
    }
}

Like all enhanced loops, this reads but cannot assign new values to elements of a primitive grid.

Standard algorithms

Sum of one row (r fixed, c varies); sum of one column (c fixed, r varies):

int colSum = 0;
for (int r = 0; r < grid.length; r++) {
    colSum += grid[r][col];
}

Row sums into a 1D array

int[] totals = new int[grid.length];
for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[r].length; c++) {
        totals[r] += grid[r][c];
    }
}

Main diagonal of a square grid: grid[i][i]. Other diagonal: grid[i][grid.length - 1 - i].

Search: return true (or the position) as soon as the target is found; return false after both loops.

Largest element and its position: start from grid[0][0].

Worked example (trace): for int[][] m = { {1, 2, 3}, {4, 5, 6} }; what is printed?

int total = 0;
for (int r = 0; r < m.length; r++) {
    for (int c = r; c < m[0].length; c++) {
        total += m[r][c];
    }
}
System.out.println(total);
  1. r = 0: c = 0, 1, 2: adds 1 + 2 + 3 = 6.
  2. r = 1: c starts at 1: adds 5 + 6 = 11.
  3. Output: 17.

Neighbors: the cells around [r][c] are [r - 1][c] (above), [r + 1][c] (below), [r][c - 1] (left) and [r][c + 1] (right). Check the bounds first, or cells on the edge will throw an exception.

if (r - 1 >= 0 && grid[r - 1][c] == target) {
    count++;
}
if (c + 1 < grid[0].length && grid[r][c + 1] == target) {
    count++;
}

Short-circuit evaluation makes the bound test protect the array access.

Processing a region: loops need not cover the whole grid. To handle only the interior (not the border), run r from 1 to length - 2 and c likewise.

2D arrays of objects: String[][] seats = new String[5][8]; holds 40 null references until each is assigned.

Linking to 1D methods: if a method sum(int[] arr) exists, the total of the grid is the sum of sum(grid[r]) over all rows. Free-response questions often expect you to reuse such a helper.

Copying a grid into a 1D array in row-major order: use a separate counter for the 1D index, increased once per element; or compute it as r * numCols + c.

Common mistakes

  • Swapping rows and columns: grid[c][r], or using grid.length for the number of columns.
  • Using grid.length as the bound for both loops in a non-square grid.
  • Accessing a neighbor without checking it exists.
  • Forgetting println after each row when printing.
  • Treating the outer enhanced-loop variable as a number; it is a row.
Check yourself

For int[][] t = new int[4][7]; what are t.length and t[0].length?

  • 28 and 7

  • 7 and 4

  • 4 and 7

  • 4 and 4

Show the answer

4 and 7

The first dimension is rows; each row has 7 columns.

6For top marks

  • Name loop variables r and c (or row and col) to avoid mixing them up.
  • Use grid.length for rows and grid[0].length for columns in every loop.
  • Free-response 2D array questions often combine traversal with a condition, such as counting cells above a value or finding the row with the largest sum.
  • Remember that a row of a 2D array can be passed to a method expecting a 1D array: sum(grid[2]).
Example

return the index of the row with the largest sum, using a row-sum helper inside a loop over rows.

Check yourself

Which expression is the bottom-right element of grid?

  • grid[−1][−1]

  • grid[grid.length][grid[0].length]

  • grid[grid[0].length − 1][grid.length − 1]

  • grid[grid.length − 1][grid[0].length − 1]

Show the answer

grid[grid.length − 1][grid[0].length − 1]

Last row, last column.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera