C++ Nested Loops

Putting one C++ loop inside another runs the inner loop to completion for every single pass of the outer loop. The inner loop runs completely for every single pass of the outer loop. This lets you work with grids, tables, and combinations, which is why nested loops show up everywhere from printing patterns to processing rows and columns.

One loop inside another

When you nest loops, think of the outer loop as choosing a row and the inner loop as walking across the columns of that row. For each value of the outer loop, the inner loop starts over and runs to completion.

Outer and inner loop

#include <iostream>
using namespace std;

int main() {
  for (int i = 1; i <= 2; i++) {
    for (int j = 1; j <= 3; j++) {
      cout << "i=" << i << " j=" << j << "\n";
    }
  }
  return 0;
}

The outer loop runs twice, and each time it does, the inner loop runs three times. That means the cout line runs a total of 2 times 3, which is 6 times.

Note: Give your loop variables different names, such as i and j, so the inner and outer counters do not clash. Reusing the same name would overwrite one loop's counter with the other's.

Building a pattern

Nested loops are great for drawing shapes. Here the outer loop controls how many rows we print, and the inner loop controls how many stars appear on each row.

A triangle of stars

#include <iostream>
using namespace std;

int main() {
  for (int row = 1; row <= 4; row++) {
    for (int star = 1; star <= row; star++) {
      cout << "*";
    }
    cout << "\n";
  }
  return 0;
}
  • The outer loop runs once per row.
  • The inner loop's count depends on the current row, so each row gets one more star.
  • The cout << "\n" after the inner loop moves to the next line.
Outer runsInner runs each timeTotal body runs
236
4416
3515

Keep in mind that nesting multiplies the work. Two loops of 1000 passes each means a million total iterations, so watch out for performance when the counts get large.