C++ Nested Loops
Nested loops in C++ are loops inside other loops. They are useful for iterating over multi-dimensional data, printing patterns, or performing repeated operations.
1. Basic Nested Loops Example
This example prints a 3x3 grid of numbers using nested for loops.
C++
Example: Basic nested for loops
#include <iostream>
using namespace std;
int main() {
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
cout << i << j << " ";
}
cout << endl;
}
return 0;
}
2. While Loop Inside For Loop
You can combine different types of loops. Here is a for loop containing a while loop.
C++
Example: While inside for loop
#include <iostream>
using namespace std;
int main() {
for(int i = 1; i <= 3; i++) {
int j = 1;
while(j <= 3) {
cout << i*j << " ";
j++;
}
cout << endl;
}
return 0;
}
3. Common Mistakes
A common mistake is forgetting to update the inner loop variable or using the wrong loop bounds, which can cause infinite loops or incorrect outputs.
Conclusion
Nested loops are essential for working with multi-dimensional data and patterns. Proper control of loop variables ensures correct and efficient execution.
Codecrown