Nested Loops — Loops Inside Loops
When one loop is not enough, put a loop inside a loop
Open interactive version (quiz + challenge)Real-world analogy
Think about a clock. The minute hand goes around the full circle (inner loop) for EACH hour the hour hand moves (outer loop). In 12 hours, the minute hand completes 12 full circles. Nested loops work the same way — the inner loop runs its entire course for each single step of the outer loop.
What is it?
Nested loops are loops placed inside other loops. The inner loop completes all its iterations for every single iteration of the outer loop. They are essential for working with 2D structures like grids, tables, and patterns, and appear frequently in competitive programming.
Real-world relevance
Nested loops appear in CP problems involving grids, matrices, pattern printing, brute-force pair checking, and 2D array processing. Many beginner CP contests include pattern-printing problems that require nested loops. Understanding them is also the first step toward grasping time complexity.
Key points
- What Are Nested Loops? — A nested loop is a loop inside another loop. The outer loop runs, and for each iteration of the outer loop, the inner loop runs completely from start to finish. If the outer loop runs R times and the inner loop runs C times, the inner body executes R × C times total.
- Rows and Columns — The most common way to think about nested loops: the outer loop controls rows (going down) and the inner loop controls columns (going across). After the inner loop finishes one row, you print a newline and the outer loop moves to the next row.
- Rectangle Star Pattern — To print a 4×5 rectangle of stars: outer loop i from 1 to 4 (rows), inner loop j from 1 to 5 (columns), print '*' in the inner loop, print endl after the inner loop. You get 4 rows of 5 stars each.
- Right Triangle Pattern — For a right triangle, the inner loop depends on the outer loop variable. Row 1 prints 1 star, row 2 prints 2 stars, row i prints i stars. Use for(int j = 1; j <= i; j++) as the inner loop. This connection between outer and inner loop is key.
- Inverted Triangle Pattern — Flip the triangle upside down by making the inner loop count from i to n: for(int j = i; j <= n; j++). Row 1 prints n stars, row 2 prints n-1 stars, and so on. Alternatively, the inner loop can run from 1 to n-i+1.
- Multiplication Table — A multiplication table is a perfect nested loop example. Outer loop i from 1 to n (rows), inner loop j from 1 to n (columns), print i*j. Each cell shows the product of its row and column number.
- Time Complexity Warning — If both loops go up to N, the inner body runs N × N = N² times. For N = 1000, that is 1 million operations (fast). For N = 100,000, that is 10 billion operations (too slow!). Always think about how many times the inner body runs in CP.
- Using Different Variables — Always use different variable names for nested loops — typically i for outer and j for inner. Using the same variable name causes the inner loop to overwrite the outer loop variable, creating confusing bugs.
Code example
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
// Rectangle of stars (n rows, n columns)
cout << "Rectangle:" << endl;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << "* ";
}
cout << endl;
}
// Right triangle
cout << "Right Triangle:" << endl;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
// Multiplication table
cout << "Multiplication Table:" << endl;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cout << i * j << "\t";
}
cout << endl;
}
return 0;
}Line-by-line walkthrough
- 1. We read n to control the size of our patterns.
- 2. Rectangle: outer loop i goes from 1 to n, controlling which row we are on.
- 3. Inner loop j goes from 1 to n, printing one star per column.
- 4. After the inner loop finishes a row, cout << endl moves to the next line.
- 5. Right triangle: the inner loop goes from 1 to i (not n), so row 1 gets 1 star, row 2 gets 2, etc.
- 6. This is the key idea — the inner loop limit depends on the outer loop variable i.
- 7. Multiplication table: inner loop prints i * j, which gives the product of the row and column.
- 8. The \t prints a tab character to align the columns neatly.
- 9. For n = 4, the rectangle has 4 × 4 = 16 stars, the triangle has 1+2+3+4 = 10 stars.
- 10. The total iterations grow as n², so large n values will take noticeably longer.
Spot the bug
#include <bits/stdc++.h>
using namespace std;
int main() {
int n = 4;
// Print right triangle
for (int i = 1; i <= n; i++) {
for (int i = 1; i <= i; i++) {
cout << "* ";
}
cout << endl;
}
return 0;
}Need a hint?
Look very carefully at the variable names in the outer loop and the inner loop. Are they the same? What happens when the inner loop modifies a variable that the outer loop is also using?
Show answer
The bug is using the same variable name 'i' for both the outer and inner loop. The inner loop declaration 'int i = 1' shadows the outer i, and the condition 'i <= i' is always true (a variable is always equal to itself), creating an infinite loop. The fix: change the inner loop variable to j: for(int j = 1; j <= i; j++).
Explain like I'm 5
Imagine you have a box of crayons and a coloring book with rows of squares. For each row (outer loop), you color every square in that row from left to right (inner loop). When you finish a row, you move down to the next row and start coloring from the left again.
Fun fact
Pattern printing with nested loops is so popular in programming education that there is an entire genre of interview questions called 'star pattern problems.' There are over 50 different star patterns (diamond, hourglass, butterfly, zigzag) and they all come down to clever use of nested loops!
Hands-on challenge
Write a program that reads N and prints an inverted right triangle of numbers. For N = 4, the output should be:
1 2 3 4
1 2 3
1 2
1
Each row starts from 1 and the number of columns decreases by one each row.
More resources
- Nested Loops & Star Patterns in C++ (YouTube)
- Nested Loops — Learn C++ (LearnCpp.com)
- Pattern Problems (HackerRank)