Nested loops and patterns
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
A loop inside a loop
- You can put one loop inside another. The inner loop runs fully for each step of the outer loop.
- This is how you work with rows and columns, or compare every pair of items.
- If the outer loop runs
Rtimes and the inner runsCtimes, the inner body runsR × Ctimes.
Rows and columns
- Think of the outer loop as the row and the inner loop as the column.
- For a block of
*, the outer loop picks a row; the inner loop prints the stars in that row. - After the inner loop finishes a row, print a newline
\nto start the next row.
Building a line, then a block
printf("*")prints one star without moving to a new line.- Print all the stars for one row first, then one
printf("\n")to end the row. - Repeat for every row, and the rows stack into a block.
#include <stdio.h>
int main(void) {
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
printf("*");
}
printf("\n"); // end the row
}
return 0;
}
Counting with nested loops
- Nested loops also count pairs. To count pairs
(i, j)withi < j, start the inner loop ati + 1. - A counter inside the inner loop adds up the matches.
- Watch the start and end values — off-by-one mistakes are common here.
Now you try
- Use an inner
printfwithout\nto build a row, then aprintf("\n")to end it. - For the function task, do not write a
main— the checker provides one.
In main, use nested loops to print a 3×3 block of * — three stars on each of three lines.
Click Run to see the output here.
In main, print a left-aligned triangle of * that is 4 rows tall: row 1 has one *, row 2 has two, up to row 4 with four.
Click Run to see the output here.
Complete int count_pairs(int n) so it returns how many pairs (i, j) satisfy 1 <= i < j <= n. Use nested loops (start the inner loop at i + 1). Do not write a main.
Click Run to see the output here.