What are Nested Loops?
A nested loop is a loop inside another loop. For each iteration of the outer loop, the inner loop completes all its iterations. They are commonly used for working with 2D data like grids, matrices, and patterns.
Example
void main() {
// Multiplication table (3x3)
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
print('$i x $j = $${i * j}');
}
}
}
Output:1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
2 x 1 = 2
...
3 x 3 = 9
Printing Patterns
// Right triangle of stars
for (int i = 1; i <= 5; i++) {
String row = '';
for (int j = 1; j <= i; j++) {
row += '* ';
}
print(row);
}
Output:*
* *
* * *
* * * *
* * * * *
Nested loops multiply execution time. A 3-level loop over N items runs N³ times. Keep nesting to a minimum and consider algorithmic alternatives for large datasets.
💪 Exercise
- Print a 5×5 multiplication table.
- Print an inverted triangle pattern using nested loops.
- Find all pairs of numbers from 1–10 whose product is greater than 50.
🧠 Quiz
1. If the outer loop runs 4 times and the inner loop runs 3 times, how many total iterations occur?
Summary
Nested loops place one loop inside another. For each outer iteration, the inner loop completes fully. Use them for grids, patterns, and 2D data. Be mindful of the O(n²) or higher time complexity they introduce.