Loops inside loops
Read · 1 of 4
The inner loop runs fully each time
With a loop inside a loop, the inner one runs from start to finish for every turn of the outer one. The outer loop usually picks the row, the inner one fills it.
Read this lesson as text
Rows and columns: patterns and tables with a loop inside a loop.
The inner loop runs fully each time
With a loop inside a loop, the inner one runs from start to finish for every turn of the outer one. The outer loop usually picks the row, the inner one fills it.
A small triangle
#include <stdio.h>
int main() {
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= row; col++) {
printf("*");
}
printf("\n");
}
return 0;
}- Line 4: Row 1.
- Line 6: The inner loop runs once (col 1 to 1).
- Line 8: End the row.
- Line 6: Row 2: the inner loop runs twice.
- Line 8: End the row.
- Line 6: Row 3: three stars.
- Line 8: Done.
Exercise: Number triangle
Read n and print n rows. Row r holds the numbers 1 to r separated by spaces:
1
1 2
1 2 3
Exercise: Centred pyramid
Read n and print a pyramid of n rows. Row r has n − r spaces, then 2r − 1 stars. For n = 3:
*
***
*****