Loops Inside Loops

You can put a loop inside another loop. For every round of the outer loop, the inner loop runs completely:

#include <iostream>
using namespace std;

int main() {
    for (int row = 1; row <= 3; row++) {
        for (int col = 1; col <= 4; col++) {
            cout << "* ";
        }
        cout << "\n";       // new line after each row
    }
    return 0;
}

Output

* * * * 
* * * * 
* * * * 

Think of it like this: Think of a clock: the minute hand (inner loop) goes all the way round for each single step of the hour hand (outer loop).

A triangle

The inner loop can depend on the outer one. Row 1 gets 1 star, row 2 gets 2 stars, and so on:

#include <iostream>
using namespace std;

int main() {
    int height = 5;
    for (int row = 1; row <= height; row++) {
        for (int i = 1; i <= row; i++) {
            cout << "*";
        }
        cout << "\n";
    }
    return 0;
}

Output

*
**
***
****
*****

A multiplication grid

#include <iostream>
using namespace std;

int main() {
    for (int a = 1; a <= 4; a++) {
        for (int b = 1; b <= 4; b++) {
            cout << a * b << "\t";
        }
        cout << "\n";
    }
    return 0;
}

Output

1	2	3	4	
2	4	6	8	
3	6	9	12	
4	8	12	16	

Tip: When nested loops confuse you, trace them with pen and paper: write down the values of the outer and inner variable for the first few rounds.

HOME LABS COMMUNITY DASHBOARD