Lesson 13 of 50 beginner

Nested Loops — Loops Inside Loops

When one loop is not enough, put a loop inside a loop

Open interactive version (quiz + challenge)

Real-world analogy

Think about a clock. The minute hand goes around the full circle (inner loop) for EACH hour the hour hand moves (outer loop). In 12 hours, the minute hand completes 12 full circles. Nested loops work the same way — the inner loop runs its entire course for each single step of the outer loop.

What is it?

Nested loops are loops placed inside other loops. The inner loop completes all its iterations for every single iteration of the outer loop. They are essential for working with 2D structures like grids, tables, and patterns, and appear frequently in competitive programming.

Real-world relevance

Nested loops appear in CP problems involving grids, matrices, pattern printing, brute-force pair checking, and 2D array processing. Many beginner CP contests include pattern-printing problems that require nested loops. Understanding them is also the first step toward grasping time complexity.

Key points

Code example

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin >> n;

    // Rectangle of stars (n rows, n columns)
    cout << "Rectangle:" << endl;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cout << "* ";
        }
        cout << endl;
    }

    // Right triangle
    cout << "Right Triangle:" << endl;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= i; j++) {
            cout << "* ";
        }
        cout << endl;
    }

    // Multiplication table
    cout << "Multiplication Table:" << endl;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
            cout << i * j << "\t";
        }
        cout << endl;
    }

    return 0;
}

Line-by-line walkthrough

  1. 1. We read n to control the size of our patterns.
  2. 2. Rectangle: outer loop i goes from 1 to n, controlling which row we are on.
  3. 3. Inner loop j goes from 1 to n, printing one star per column.
  4. 4. After the inner loop finishes a row, cout << endl moves to the next line.
  5. 5. Right triangle: the inner loop goes from 1 to i (not n), so row 1 gets 1 star, row 2 gets 2, etc.
  6. 6. This is the key idea — the inner loop limit depends on the outer loop variable i.
  7. 7. Multiplication table: inner loop prints i * j, which gives the product of the row and column.
  8. 8. The \t prints a tab character to align the columns neatly.
  9. 9. For n = 4, the rectangle has 4 × 4 = 16 stars, the triangle has 1+2+3+4 = 10 stars.
  10. 10. The total iterations grow as n², so large n values will take noticeably longer.

Spot the bug

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n = 4;
    // Print right triangle
    for (int i = 1; i <= n; i++) {
        for (int i = 1; i <= i; i++) {
            cout << "* ";
        }
        cout << endl;
    }
    return 0;
}
Need a hint?
Look very carefully at the variable names in the outer loop and the inner loop. Are they the same? What happens when the inner loop modifies a variable that the outer loop is also using?
Show answer
The bug is using the same variable name 'i' for both the outer and inner loop. The inner loop declaration 'int i = 1' shadows the outer i, and the condition 'i <= i' is always true (a variable is always equal to itself), creating an infinite loop. The fix: change the inner loop variable to j: for(int j = 1; j <= i; j++).

Explain like I'm 5

Imagine you have a box of crayons and a coloring book with rows of squares. For each row (outer loop), you color every square in that row from left to right (inner loop). When you finish a row, you move down to the next row and start coloring from the left again.

Fun fact

Pattern printing with nested loops is so popular in programming education that there is an entire genre of interview questions called 'star pattern problems.' There are over 50 different star patterns (diamond, hourglass, butterfly, zigzag) and they all come down to clever use of nested loops!

Hands-on challenge

Write a program that reads N and prints an inverted right triangle of numbers. For N = 4, the output should be: 1 2 3 4 1 2 3 1 2 1 Each row starts from 1 and the number of columns decreases by one each row.

More resources

Open interactive version (quiz + challenge) ← Back to course: CP Zero to Hero