Nested Loops
What you'll learn: How to place one loop inside another to handle multi-dimensional or multi-level repetitive tasks.
What Are Nested Loops?
A nested loop is simply a loop placed inside the body of another loop. The inner loop completes all its iterations for each single iteration of the outer loop. Think of it like the minute hand on a clock: for every hour (outer loop), the minute hand completes 60 full rotations (inner loop).
How They Work
When you nest loops, the structure looks like this in pseudocode:
for each item in outer collection:
for each item in inner collection:
do something with both items
The inner loop runs to completion every time the outer loop advances by one step.
A Concrete Example
Imagine printing a multiplication table. You need one loop for the rows (outer) and another for the columns (inner):
for row from 1 to 5:
for column from 1 to 5:
print(row * column)
print newline
When row is 1, the inner loop runs 5 times (columns 1-5). Then row becomes 2, and the inner loop runs another 5 times, and so on.
Common Use Cases
- Processing 2D grids or matrices
- Generating all pairs of items from two collections
- Creating patterns or shapes with characters
- Comparing every element with every other element
Performance Note
Be careful: if the outer loop runs n times and the inner loop runs m times, the total operations are n × m. Nested loops can become slow with large datasets.
Key Takeaway: Nested loops let you solve problems requiring multiple levels of repetition by placing one loop inside another—the inner loop completes fully for each iteration of the outer loop.