Nested Loops in C++
Concept of Nesting
A nested loop is a loop placed inside another loop. The inner loop runs all its iterations for each single iteration of the outer loop.
This is commonly used for 2D arrays, matrices, and grid-based problems.
Matrix Example
#include <iostream>
using namespace std;
int main() {
for (int row = 0; row < 3; row++) { // Outer loop
for (int col = 0; col < 3; col++) { // Inner loop
cout << "(" << row << "," << col << ") ";
}
cout << endl;
}
return 0;
}
(0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)
Execution flow:
Outer loop (row = 0) → Inner loop runs col = 0, 1, 2
Outer loop (row = 1) → Inner loop runs col = 0, 1, 2
Outer loop (row = 2) → Inner loop runs col = 0, 1, 2
Dependent Inner Loop (Triangles)
Inner-loop bounds can depend on the outer index—useful for triangular patterns:
#include <iostream>
using namespace std;
int main() {
int n = 5;
for (int i = 1; i <= n; ++i) { // rows
for (int j = 1; j <= i; ++j) { // columns up to i
cout << "*";
}
cout << "\n";
}
return 0;
}
* ** *** **** *****
Multiplication Table
A practical use of nested loops is generating tables:
#include <iostream>
using namespace std;
int main() {
for (int r = 1; r <= 5; ++r) {
for (int c = 1; c <= 5; ++c) {
cout << r * c << "\t";
}
cout << "\n";
}
return 0;
}
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
Order & Locality with 2D Arrays
C++ stores multi-dimensional arrays in row-major order. Iterate rows in the outer loop and columns in the inner loop for better cache locality.
int grid[3][4]{};
int sum = 0;
for (int r = 0; r < 3; ++r) {
for (int c = 0; c < 4; ++c) {
sum += grid[r][c]; // contiguous access by columns inside each row
}
}
Performance Considerations
Keep the most frequently changing loop innermost for efficiency.
Avoid heavy calculations inside the innermost loop.
Prefer algorithms that reduce work (early exits, pruning) over micro-optimizations.
Common Pitfalls
- Forgetting to reset inner-loop variables when needed
- Off-by-one errors in loop bounds
- Reusing the same loop variable name in inner and outer loops
- Modifying loop bounds inside the loop body unintentionally