5.5 — Loops inside loops
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.
Tip: press ← / → to move between lessons, / to search.