Topic 4.13 — Traversing 2D Arrays

Goal: traverse every element in a 2D array using nested loops, choose correct loop bounds, and understand common traversal patterns (row-major, column-major).

The big idea

Traversing a 2D array usually means nested loops: the outer loop picks the row, the inner loop picks the column.

The #1 rule: use grid.length for rows and grid[r].length for columns.

Standard (row-major) traversal

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

This is the default pattern you should expect most often.

Example: sum all elements

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

Example: count matches

Count how many values are 0.

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

Neighbor access needs bounds

If you use grid[r][c+1], make sure c stops at length - 2.

// compare each cell with the one to its right
for (int r = 0; r < grid.length; r++) {
  for (int c = 0; c < grid[r].length - 1; c++) {
    if (grid[r][c] < grid[r][c + 1]) {
      // ...
    }
  }
}

Column-major traversal (less common)

This visits by columns first. It usually assumes a rectangular array.

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

Jagged arrays: don’t assume equal column counts

For jagged arrays, different rows can have different lengths—so always use grid[r].length in the inner loop.

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

Quick self-check

  1. Which loop variable usually represents the row? the column?
  2. What does grid.length mean?
  3. Why is grid[r].length safer than grid[0].length?
  4. What bounds do you use to compare grid[r][c] with grid[r][c+1]?
  5. Write code to find the smallest value in the entire 2D array.

← Back to Unit 4 topics