C++ Nested Loops
A nested loop in C++ is a loop inside another loop. The inner loop runs completely for every single iteration of the outer loop. Nested loops are commonly used when working with tables, patterns, matrices, or multidimensional data.
Any type of loop (for, while, or do while) can be nested inside another loop.
Syntax
for(initialization; condition; increment) {
for(initialization; condition; increment) {
// inner loop code
}
// outer loop code
}
How Nested Loops Work
- The outer loop executes first.
- For every iteration of the outer loop, the inner loop runs completely.
- Once the inner loop finishes, the outer loop continues to the next iteration.
Example Program
This example prints a simple number pattern using nested loops.
#include <iostream>
using namespace std;
int main() {
for(int i = 1; i <= 3; i++) {
for(int j = 1; j <= 3; j++) {
cout << j << " ";
}
cout << endl;
}
return 0;
}
Output
1 2 3 1 2 3 1 2 3
Example: Star Pattern
#include <iostream>
using namespace std;
int main() {
for(int i = 1; i <= 5; i++) {
for(int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
return 0;
}
Output
* * * * * * * * * * * * * * *
Important Notes
- Nested loops are often used for working with patterns, matrices, and tables.
- The inner loop runs fully for each iteration of the outer loop.
- Too many nested loops can make programs slower, especially with large data.
Next Topic
Next, learn about C++ Functions.