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 order | The outer loop | Safe for any shape |
|---|---|---|
| Row by row | Over rows | Yes |
| Column by column | Over cell positions | Only if all are equal |
Example 1 — why the natural order is safe
- It asks each row its length.
- So it does not assume they are equal.
- It works for any shape.
Example 2 — why the second is dangerous on an uneven shape
- The outer position is settled by one row.
- And a short row does not reach it.
- And the result is an out-of-range error.