Control Flow By the CodeCracker Team

Nested Loops and 2D Grids: Understanding Loops Inside Loops

Master nested loops by visualizing how outer and inner counters advance together, traverse 2D game boards row by row, and avoid common loop variable bugs.

In This Article

  • Trace how an inner loop completes all of its iterations for every single tick of the outer loop.
  • Calculate total execution count by multiplying outer iterations by inner iterations (rows * cols).
  • Traverse 2D tile maps and coordinate grids systematically using (row, col) loop pairs.
  • Let the inner loop's limit depend on the outer loop variable to generate triangular and diagonal patterns.

How a Loop Inside a Loop Works

When you first encounter a nested loop—a loop placed inside the body of another loop—it can feel disorienting to keep track of two counters changing at different speeds. Fortunately, you already use a nested loop system every day whenever you look at a clock.

Think about how the hour hand and the minute hand move on a clock face. For the hour hand (the outer loop) to advance by just 1 hour, the minute hand (the inner loop) must complete an entire cycle of 60 minutes from 0 to 59. Only after the minute hand finishes all 60 steps does the hour hand tick forward to the next hour—whereupon the minute hand resets to 0 and runs through all 60 minutes again. Over a 12-hour cycle, the hour hand ticks 12 times, while the minute hand ticks 12 * 60 = 720 times.

Code with nested loops follows this exact same rule: for every single iteration of the outer loop, the inner loop runs from start to finish completely.

Counting Total Iterations: Multiplication in Action

Suppose a puzzle room has 4 rows of tiles, and each row contains 5 tiles from left to right. If you write an outer loop that runs 4 times (once per row) and place an inner loop inside it that runs 5 times (once per column in that row), any statement inside the inner loop will execute 4 * 5 = 20 times in total.

Understanding this multiplicative behavior is essential both for predicting what your program will do and for estimating performance. If an outer loop runs 1,000 times and an inner loop runs 1,000 times, the inner body executes 1,000 * 1,000 = 1,000,000 times. In computer science, an algorithm that processes an N-by-N grid using two nested loops is said to take quadratic work, written as O(N^2).

Traversing a 2D Game Board Row by Row

Almost every 2D game—whether it is chess, Minesweeper, a sliding tile puzzle, or a top-down maze—stores its board as a two-dimensional grid of cells indexed by row and col. By convention in programming, row 0 is the top row, and column 0 is the leftmost column.

To inspect or draw every cell on the board, we use the outer loop to select which row we are currently visiting, and the inner loop to sweep across every col within that row from left to right. When the inner loop reaches the end of a row, execution exits the inner loop, prints a newline (or moves the robot down to the start of the next row), and begins the next outer iteration.

Visual Block Logic

FOR row FROM 0 TO 2:
  FOR col FROM 0 TO 3:
    inspect_tile(row, col)
  move_to_next_row()

Python

rows = 3
cols = 4
for row in range(rows):
    for col in range(cols):
        print(f"({row},{col})", end=" ")
    print()  # Newline after each row

C++

int rows = 3;
int cols = 4;
for (int row = 0; row < rows; ++row) {
    for (int col = 0; col < cols; ++col) {
        std::cout << "(" << row << "," << col << ") ";
    }
    std::cout << "
"; // Newline after each row
}

If you run the Python or C++ code above, it produces a clean 3-by-4 coordinate table:

(0,0) (0,1) (0,2) (0,3)
(1,0) (1,1) (1,2) (1,3)
(2,0) (2,1) (2,2) (2,3)

Look at how the numbers change across the first line: row stays frozen at 0 while col counts 0, 1, 2, 3. Then the inner loop finishes, starts a new line, the outer loop increments row to 1, and col starts fresh at 0 again.

Key Idea: Placement matters! Statements placed inside the inner loop run once per cell (rows * cols times). Statements placed inside the outer loop after the inner loop run only once per row (rows times).

Dynamic Inner Bounds: Triangles and Diagonals

In the grid example above, the inner loop always ran the exact same number of times (cols = 4) regardless of which row it was on. What happens if we make the inner loop's stopping condition depend on the outer loop's current variable?

Suppose we want to build a staircase pyramid where row 0 has 1 block, row 1 has 2 blocks, row 2 has 3 blocks, and row r has r + 1 blocks. By setting the inner loop to run from 0 up to row (inclusive), each row automatically grows one unit wider than the row above it:

Visual Block Logic

FOR row FROM 0 TO 3:
  FOR col FROM 0 TO row:
    place_brick(row, col)

Python

for row in range(4):
    for col in range(row + 1):
        print("#", end=" ")
    print()

C++

for (int row = 0; row < 4; ++row) {
    for (int col = 0; col <= row; ++col) {
        std::cout << "# ";
    }
    std::cout << "
";
}

Three Common Nested Loop Mistakes

  1. Reusing the same loop counter name: If you name both the outer counter and the inner counter i (e.g., for i in range(4): for i in range(4):), the inner loop hijacks the outer loop's variable! Always use distinct, descriptive names like row and col, or at least r and c.
  2. Copy-paste condition typos in C++: When writing for (int c = 0; c < cols; ++r), accidentally typing ++r instead of ++c in the inner loop causes c to stay at 0 forever while r shoots past the board boundary.
  3. Resetting accumulator variables in the wrong scope: If you want to calculate the sum of coins in each individual row, you must initialize int row_sum = 0; at the top of the outer loop (before the inner loop starts) so it resets to zero for every new row.

Searching a 2D Grid and Breaking Early

Often you traverse a 2D grid not to print every tile, but to locate a specific target—such as finding which square holds the player's starting spawn point 'S'. Keep in mind that a break statement inside the inner loop only exits the innermost loop; the outer loop will continue to the next row! If you want to stop searching the entire 2D grid as soon as the target is found, the cleanest technique is to wrap the nested loop inside a helper function (such as find_start_tile(grid)) and use return (row, col) directly from inside the inner loop, which immediately exits both loops at once and hands back the coordinates.

Practice Exercise: Checkerboard Generator

On an 8-by-8 chessboard, squares alternate between dark (#) and light (.). A neat mathematical property of a grid is that the sum of a cell's coordinates (row + col) is even on every dark square and odd on every light square (when (0, 0) is dark).

Write a nested loop in Python or C++ that takes an integer N = 6 and prints an N-by-N checkerboard pattern using (row + col) % 2 == 0 to decide whether to print # or . at each cell. Bonus: count how many total # squares were printed when N = 5.