Nested loops
Nested loops and practical examples for them
Nested Loops
A nested loop is simply a loop placed inside another loop. For every single iteration of the outer loop, the inner loop runs completely from start to finish. This makes nested loops the natural tool for working with grids, tables, pairs of values, and any problem that requires two independent counters.
Basic Structure
Output:
The outer loop runs 3 times. Each time, the inner loop runs 3 times completely. Total iterations: 3 × 3 = 9.
Multiplication Table
A classic use of nested loops — for each row i, print i * j for every column j:
Output:
print() with no arguments at the end of the outer loop moves to the next line after each row.
Printing Patterns
Nested loops are perfect for printing shapes. The outer loop controls rows, the inner loop controls columns.
Rectangle of stars
Output:
Right triangle
Output:
The inner loop runs i times on row i, creating the triangle shape.
Inverted triangle
Output:
Iterating Over All Pairs
Nested loops let you consider every combination of two values. A common CP task: find all pairs (a, b) where both are in range and satisfy some condition.
For n = 10:
Prime Number Check
To check if a number n is prime, try dividing it by every number from 2 to n-1. If none divide evenly, it is prime:
Now use nested loops to print all primes up to some limit:
For limit = 30:
Time Complexity
Each level of nesting multiplies the number of iterations. If the outer loop runs n times and the inner loop runs n times, the total is n^2 iterations — we say the time complexity is O(n^2):
With n = 10,000 this would already be 100,000,000 iterations — likely too slow for a competitive programming problem with a 1-second time limit. Always think about how many total iterations your nested loops will perform.
A triple nested loop would be O(n^3):
break in Nested Loops
break only exits the innermost loop it is placed in, not all loops at once:
If you need to exit multiple levels at once, one clean approach is to use a flag variable: