5.5 — Loops inside loops

📘 Chapter 5⏱ about 1 min read✍️ Beginner friendly
Read one box at a time. No rush.

Nested loops#

You can put a loop inside another loop. The inner loop runs fully for each trip of the outer loop.

C++
for (int row { 1 }; row <= 3; ++row){    for (int col { 1 }; col <= 4; ++col)    {        std::cout << '*';    }    std::cout << '\n';}
Output
************

A triangle#

Make the inner loop depend on the outer one:

C++
for (int row { 1 }; row <= 4; ++row){    for (int i { 0 }; i < row; ++i)    {        std::cout << '#';    }    std::cout << '\n';}
Output
##########
Key idea

3 outer trips × 4 inner trips = 12 stars. Nested loops multiply.

Finished reading? Tick it off. Your progress is saved in this browser.

Tip: press ← / → to move between lessons, / to search.