Nested Loops in C++ (original) (raw)

Last Updated : 14 Jan, 2026

Nested loop means a loop statement inside another loop statement. That is why nested loops are also called as "loop inside loop".

1. Nested For loop

A nested for loop means using one for loop inside another for loop, where the inner for loop executes fully for every single iteration of the outer for loop.

Example Program to Print Identity Matrix Using Nested for Loops

CPP `

#include using namespace std;

int main() { int n = 4; for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == j) cout << "1 "; else cout << "0 "; } cout << endl; } return 0; }

`

Output

1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1

**Explanation:

Nested-for-Loop

2. Nested While loop

A nested while loop means using one while loop inside another while loop, where the inner while loop executes completely for every single iteration of the outer while loop.

Example Program to Print a Square Pattern Using Nested while Loops

C++ `

#include using namespace std;

int main() { int i = 1, j; int n = 4; while (i <= n) { // Outer while loop j = 1; while (j <= n) { // Inner while loop cout << "* "; j++; } cout << endl; i++; } return 0; }

`

Output





**Explanation:

Nested-do-while-Loop

**3. Nested Do-While loop

A nested do-while loop means using one do-while loop inside another do-while loop, where the inner loop runs completely for every single iteration of the outer loop.

Example Program to Print a Star Triangle Using Nested do-while Loops

C++ `

#include using namespace std;

int main() { int i = 1, j; int n = 4;

do {
    j = 1;
    do {
        cout << "* ";
        j++;
    } while (j <= i);
    cout << endl;
    i++;
} while (i <= n);

return 0;

}

`

Output

*



**Explanation:

**Note: There is no rule that a loop must be nested inside its own type. In fact, there can be any type of loop nested inside any type and to any level.

C++ `

#include using namespace std;

int main() { int i = 1;

do {                                  // Outer do-while loop
    int j = 1;
    while (j <= 2) {                  // Inner while loop
        for (int k = 1; k <= 3; k++) { // Inside for loop
            cout << i << j << k << " ";
        }
        cout << endl;
        j++;
    }
    i++;
} while (i <= 2);
return 0;

}

`

Output

111 112 113 121 122 123 211 212 213 221 222 223

**Explanation:

Uses of Nested Loops