Topic 19 of 83
Nested Loops
Overview
Placing a loop inside another loop is known as nesting. It's essential for working with multi-dimensional arrays, matrices, and generating patterns.
Syntax
cpp
for (int i = 0; i < 3; i++) { // Outer loop
for (int j = 0; j < 3; j++) { // Inner loop
cout << "(" << i << "," << j << ") ";
}
cout << endl;
}Common Pitfalls
- Accidentally using the outer loop variable (e.g., `i`) inside the inner loop's condition or update step.
- High performance costs for deeply nested loops.
Interview Tips
- Nested loops dramatically increase time complexity (e.g., O(N^2)). Interviewers will often ask you to optimize an O(N^2) nested loop solution into an O(N) solution using a Hash Map.
Real-World Example
Printing a multiplication table matrix.
example
cpp
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
cout << i * j << "\t";
}
cout << "\n";
}
return 0;
}