Lesson 5 of 6 · Control Flow · 3 min read · Updated
Nested loops and patterns
A loop inside a loop — tables, grids and the star and number patterns every C course asks for.
Put one loop inside another and the inner loop runs completely for every single turn of the outer loop. Think of rows and columns: the outer loop picks the row, the inner loop walks across it.
#include <stdio.h>
int main(void)
{
for (int i = 1; i <= 3; i++) { /* rows */
for (int j = 1; j <= 4; j++) { /* columns */
printf("%4d", i * j);
}
printf("\n"); /* end of the row */
}
return 0;
}
1 2 3 4
2 4 6 8
3 6 9 12
3 rows × 4 columns = 12 prints. %4d gives every number four spaces so the columns line up, and the printf("\n") after the inner loop starts the next row.
Pattern 1: a right triangle of stars
#include <stdio.h>
int main(void)
{
int n = 4;
for (int row = 1; row <= n; row++) {
for (int star = 1; star <= row; star++) {
printf("* ");
}
printf("\n");
}
return 0;
}
*
* *
* * *
* * * *
The trick in every pattern: work out how many things row number row needs. Here row 1 has 1 star, row 2 has 2 — so the inner loop runs row times.
Pattern 2: a number triangle
#include <stdio.h>
int main(void)
{
for (int row = 1; row <= 4; row++) {
for (int k = 1; k <= row; k++) {
printf("%d ", k);
}
printf("\n");
}
return 0;
}
1
1 2
1 2 3
1 2 3 4
Pattern 3: a pyramid
#include <stdio.h>
int main(void)
{
int n = 4;
for (int row = 1; row <= n; row++) {
for (int s = 1; s <= n - row; s++) { /* spaces first */
printf(" ");
}
for (int star = 1; star <= 2 * row - 1; star++) {
printf("*");
}
printf("\n");
}
return 0;
}
*
***
*****
*******
A pyramid needs two inner loops per row: first n - row spaces to push the stars to the centre, then 2 × row − 1 stars (1, 3, 5, 7).
Warning
Use a different variable for each loop. Reusing i in the inner loop changes the outer counter too, and the pattern breaks or the program never ends.
An outer loop runs 5 times and its inner loop runs 3 times per turn. How many times does the inner body run?
Try this now
- Print an inverted star triangle: 4 stars, then 3, 2, 1.
- Print Floyd's triangle: 1 / 2 3 / 4 5 6 / 7 8 9 10 (keep one counter that never resets).
- Print a full multiplication table from 1 × 1 to 10 × 10 with aligned columns.
- Print a hollow square of stars 5 wide (stars only on the border).
Create a free account to save your progress, or sign in.