Introduction to loops inside loops
What you'll learn: How to place one loop inside another to handle multi-dimensional tasks like grids or repeating patterns.
The "Loop-in-a-Loop" Concept
Up until now, we have used loops to repeat a block of code. But what happens when the task you want to repeat is itself a loop? This is called a nested loop.
Think of a nested loop like a digital clock. The "minutes" loop runs 60 times, but it only completes one full cycle after the "seconds" loop has finished its own 60-second cycle. The outer loop (minutes) moves slowly, while the inner loop (seconds) completes its entire journey every time the outer loop ticks once.
How it works in C
In C, we typically use two for loops to achieve this. The program enters the outer loop, hits the inner loop, and stays there until the inner loop's condition becomes false. Only then does it jump back to the outer loop to start the next iteration.
Here is how you might print a small grid of stars:
#include <stdio.h>
int main() {
// Outer loop handles the rows
for (int row = 1; row <= 3; row++) {
// Inner loop handles the columns (stars in each row)
for (int col = 1; col <= 5; col++) {
printf("*");
}
// After the inner loop finishes a row, move to a new line
printf("\n");
}
return 0;
}
Visualizing the execution
In the code above, the outer loop runs 3 times (representing 3 rows). However, every time the outer loop runs once, the inner loop runs 5 times.
- The outer loop starts at
row = 1. - The inner loop runs for
col = 1, 2, 3, 4, 5, printing five stars. - The inner loop finishes. The program prints a newline (
\n). - The outer loop moves to
row = 2, and the process repeats.
By the time the program finishes, the inner printf will have executed a total of 15 times (3 rows × 5 columns). This structure is the foundation for working with coordinate systems, game boards, and complex data tables.
Key takeaway
A nested loop performs a full cycle of the inner loop for every single iteration of the outer loop.