Nested Loops
A loop can contain another loop. This is called a nested loop. In each iteration of the outer loop, the inner loop runs all the way through. Let's draw a rectangle of stars, 3 rows with 5 stars each:
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 5; column++) {
printf("*");
}
printf("\n");
}This prints:
*****
*****
*****The outer loop starts with the first row, and the inner loop prints five stars. printf("*") has no \n, so the stars go next to each other on one line. After the inner loop, printf("\n") ends the row. Only then does the outer loop move on to the second row, and the inner loop prints five stars again. The inner block runs 3 × 5 = 15 times. Give the variables of the two loops different names (here row and column), so that you know which is which.
Look at where printf("\n"); is: after the closing brace of the inner loop, but still inside the outer loop. It runs each time the inner loop has printed a whole row. Inside the inner loop, it would put every star on its own line. After the outer loop, it would put all 15 stars on one long line.
The inner loop can use the variable of the outer loop. This multiplication table prints row * column with a space after it:
for (int row = 1; row <= 3; row++) {
for (int column = 1; column <= 5; column++) {
printf("%d ", row * column);
}
printf("\n");
}1 2 3 4 5
2 4 6 8 10
3 6 9 12 15 Each row ends with a space too. You can't see it, and here it doesn't matter.
The condition of the inner loop can use the outer variable as well. With column <= row, the inner loop runs once in the first row, twice in the second, and so on, and the stars make a triangle:
for (int row = 1; row <= 4; row++) {
for (int column = 1; column <= row; column++) {
printf("*");
}
printf("\n");
}*
**
***
****One more thing: break in the inner loop ends only the inner loop. The outer loop goes on with its next iteration.
Instructions
Draw a rectangle of stars with 4 rows and 6 stars in each row. Use two nested for loops: an outer loop with the variable row and an inner loop with the variable column. The inner loop prints one * without \n. After it, still inside the outer loop, printf("\n"); ends the row.
Below the rectangle, print a multiplication table from 1 to 5: five rows with five numbers each, separated by spaces. The first row is 1 2 3 4 5, the second one 2 4 6 8 10 and the last one 5 10 15 20 25. Use two nested for loops again, and end each row with printf("\n"); in the outer loop.
Start programming for free
9/11