A girl and a robot thinking together

Let’s think it through · Start with a story

A classroom has two rows of seats, with three seats in each row. The girl asks the robot to number every seat.

Break down the process

Follow the numbered steps, then explain them in your own words
  1. Outer loop: row 1Inner loop labels 3 seats
  2. Outer loop: row 2Inner loop labels 3 more
  3. Total2 × 3 = 6

A nested loop runs a complete inner repetition for each action of the outer loop.

Keep the row fixed while you visit each column in that row, then move to the next row. Track the two counters separately to avoid mixing them up.

01What is a nested loop?

A loop written inside the body of another loop is called a nested loop.

for (int row = 1; row <= 2; row++) {
    for (int col = 1; col <= 3; col++) {
        std::cout << row << ',' << col << '\n';
    }
}

02How does it run?

row = 1→col = 1, 2, 3↓row = 2→col = 1, 2, 3

Each time the outer loop begins an iteration, the inner loop starts over from its own initialization.

03Why are nested loops useful for tables?

A table naturally has two directions: rows and columns.

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

The outer loop can control the rows, and the inner loop can control the columns.

04How many times do two loops run?

If the outer loop runs 4 times and the inner loop runs 5 times during each outer iteration, the innermost code runs:

4 × 5 = 20 times

This is an important foundation for understanding algorithm efficiency later.

05Can inner and outer variables have the same name?

Some scopes allow code that shadows an outer name, but beginners should avoid doing this.

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 4; j++) {
        // i is the outer counter; j is the inner counter
    }
}

Different, meaningful names make the code easier to understand.

06Can we use three or four nested loops?

The syntax allows it, but more levels are harder to read and the number of executions can grow quickly.

When you study algorithmic complexity, you will see why nested loops often mean more work.

What you have learned

  • A loop can be placed inside another loop.
  • Each outer iteration usually runs the inner loop through its complete cycle.
  • Nested loops are useful for rows and columns, coordinates, and two-dimensional data.
  • To find the total work, consider how the iteration counts of each level combine.
  • The more levels there are, the more carefully you need to track variables.

Next: What Do break and continue Do?

Your turn

With 3 rows and only 2 seats to label in each row, how many labels will be placed?

Have an answer? Click to see the explanation

Six. You can list (1,1), (1,2), (2,1), (2,2), (3,1), and (3,2) to check that none are missing.