C Nested Loops
You can place one loop inside another. This is called a nested loop, and it is the standard way to work with grids, tables, and shapes such as rows and columns.
Nested Loops
A nested loop is a loop inside another loop. The outer loop runs once, and for each of its passes the inner loop runs all the way through. If the outer loop runs 3 times and the inner loop runs 2 times, the inner body runs a total of 6 times.
An outer and inner loop
#include <stdio.h>
int main() {
for (int i = 1; i <= 2; i++) {
printf("Outer: %d\n", i);
for (int j = 1; j <= 3; j++) {
printf(" Inner: %d\n", j);
}
}
return 0;
}For each value of i in the outer loop, the inner loop counts j from 1 to 3. So you see Outer: 1 followed by three inner lines, then Outer: 2 followed by three more inner lines.
Printing a grid of stars
#include <stdio.h>
int main() {
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 4; col++) {
printf("*");
}
printf("\n");
}
return 0;
}The inner loop prints 4 stars on one line, and the outer loop repeats that 3 times. The result is a rectangle of stars, 3 rows tall and 4 columns wide. The printf with a newline sits in the outer loop so each row ends cleanly.
- The outer loop controls the rows.
- The inner loop controls the columns within each row.
- Total passes equal outer count multiplied by inner count.