dev only
Nested Iteration
A Loop Inside a Loop
Nesting one loop inside another means the inner loop runs to completion for every single pass of the outer one:
for (int row = 0; row < 8; row++)
{
for (int col = 0; col < 8; col++)
{
visionGrid[row][col] = sampleCell(row, col);
}
}
For each value of row, the inner loop runs all the way through every col value before the outer loop advances to the next row. The inner loop restarts from scratch each time.
Why This Matters
Nested loops are the natural shape for anything grid-like: scanning a 2D vision frame, checking every pair of sensors against each other, or generating a table of test cases. (2D arrays, which pair naturally with nested loops, get their own full chapter — Ch.10.)
Common Pitfalls
- Reusing the same loop variable name for both loops.
for (int i ...)nested inside anotherfor (int i ...)won't compile — the inner declaration shadows/conflicts with the outer one in the same scope. Use distinct names (row/col,i/j). - Assuming the inner loop's variable persists across outer iterations. It doesn't — a loop variable declared in the
forheader is freshly initialized every time that loop starts, including every restart of an inner loop.
Key Takeaways
- A loop nested inside another runs completely, every single time the outer loop takes one step.
- Nested loops are the standard shape for anything grid-shaped — rows and columns, pairs of items, tables of test cases.
- Use distinct loop variable names for nested loops (
row/col, noti/i).
Derived from csawesome-2026: unit-2-selection-and-iteration/2.11-nested-iteration.md (CSA 2.11)