C++ Nested Loops

πŸ”πŸ” C++ Nested Loops

Nested Loop ka matlab hota hai ek loop ke andar doosra loop.
Ye zyada tar patterns, tables, matrices, grids ke liye use hota hai.


πŸ”Ή 1. Syntax

for (initialization; condition; update) {
for (initialization; condition; update) {
// inner loop code
}
}

πŸ‘‰ Outer loop har iteration ke liye inner loop poora chalta hai.


πŸ”Ή 2. Basic Nested Loop Example

for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
cout << i << j << " ";
}
}

Output:

11 12 13 21 22 23 31 32 33

πŸ”Ή 3. Multiplication Table (1 to 3)

for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 10; j++) {
cout << i * j << " ";
}
cout << endl;
}

πŸ”Ή 4. Pattern Printing Example

⭐ Star Pattern

for (int i = 1; i <= 4; i++) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}

Output:

*
* *
* * *
* * * *

πŸ”Ή 5. Nested while Loop

int i = 1;

while (i <= 3) {
int j = 1;
while (j <= 3) {
cout << i << j << " ";
j++;
}
cout << endl;
i++;
}


πŸ”Ή 6. Nested do-while Loop

int i = 1;

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


πŸ”Ή 7. Loop Iteration Count (Important)

for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
// Total iterations = 3 Γ— 3 = 9
}
}

❌ Common Mistakes

for (int i = 1; i <= 3; i++) {
for (int i = 1; i <= 3; i++) { // ❌ same variable name
cout << i;
}
}

βœ” Correct:

for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
cout << j;
}
}

πŸ“Œ Summary

  • Nested loops = loop inside loop

  • Inner loop completes fully for each outer loop

  • Used in patterns, tables, matrices

  • Time complexity increases (O(nΒ²))

You may also like...