Grade 12 Computer Science · Two-dimensional arrays

Two orders of traversal

Why one of them is natural and the other requires thought.

The same cells, the same total, and only one crashes

Two nested loops pass over the same grid and compute the same total. The only difference: which loop is on the outside. On most grids both work, and on one particular grid one of them fails. Which one, and which grid?

Traversing a grid means two loops, one inside the other. The choice of who is outside and who inside is not stylistic: it settles the order of visiting, and in some questions only one order gives a right answer.

// row by row — the natural order, safe for any shape
for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[r].length; c++) {   // ask each row
        total += grid[r][c];
    }
}

// column by column — only if every row has the same length
for (int c = 0; c < grid[0].length; c++) {
    for (int r = 0; r < grid.length; r++) { ... }
}

When column by column is required

Any question whose answer accumulates along a column requires the second order — the total of each column, the maximum in each column, checking whether a column is full. It can also be achieved in the natural order by accumulating into an array of results, one per column, and joining as one goes. Both ways are correct, and the second is more efficient in large structures because it passes over memory in the order in which it is arranged.

The orderThe outer loopSafe for any shape
Row by rowOver rowsYes
Column by columnOver cell positionsOnly if all are equal

Example 1 — why the natural order is safe

  1. It asks each row its length.
  2. So it does not assume they are equal.
  3. It works for any shape.

Example 2 — why the second is dangerous on an uneven shape

  1. The outer position is settled by one row.
  2. And a short row does not reach it.
  3. And the result is an out-of-range error.
In column-by-column order, grid[0].length would fix 3 positions for every row — and row 1 is too short.