Skip to content

Nested loops in C++ with a star pattern example

Understand nested loops in C++ by printing a star triangle, and learn how the inner and outer loops work together.

Published 2026-11-28

A nested loop is a loop inside another loop. The outer loop picks a row; the inner loop does the work for that row.

Pattern printing is the classic exercise because you can see every step on the screen. Change the numbers below and watch how the shape changes.

Nested loops run inner × outer times, so they get slow quickly on big inputs — a first taste of Big-O thinking.

#include <iostream>
int main() {
    for (int row = 1; row <= 4; ++row) {
        for (int col = 1; col <= row; ++col) std::cout << '*';
        std::cout << '\n';
    }
}

Learn it properly — free lessons

← All posts