A loop can contain another loop. The inner loop runs completely for every round of the outer loop:
#include <stdio.h>
int main() {
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 4; col++) {
printf("* ");
}
printf("\n");
}
return 0;
}Output
* * * * * * * * * * * *
Think of it like this: Think of a clock. The minute hand (inner loop) goes all the way round 60 times for every one step of the hour hand (outer loop).
Drawing a triangle
Make the inner loop depend on the outer counter, and you get a triangle:
#include <stdio.h>
int main() {
int n = 5;
for (int row = 1; row <= n; row++) {
for (int i = 1; i <= row; i++) {
printf("*");
}
printf("\n");
}
return 0;
}Output
* ** *** **** *****
A multiplication table
#include <stdio.h>
int main() {
for (int a = 1; a <= 5; a++) {
for (int b = 1; b <= 5; b++) {
printf("%4d", a * b);
}
printf("\n");
}
return 0;
}Output
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25
Tip:
%4dgives every number the same width, so the columns line up nicely.
Remember: Use different counter names for each loop (
row/colori/j) so they don't get mixed up.