Nested loops and patterns · ネストされたループとパターン
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.
Common mistakes
- The inner loop runs fully for each single turn of the outer loop.
- Check the bounds so a pattern has no extra or missing row.
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. · main内でネストされたループを使用して、3×3の*ブロックを出力 — 3行それぞれに星印を3つ表示します。
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. · main内で左揃えの*の三角形を4段分出力してください:1行目に1つの*、2行目に2つ、4行目に4つまで。
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. · int count_pairs(int n) を完成させて、(i, j) のペアが 1 <= i < j <= n を満たす数を返してください。ネストループを使用してください(内側のループは i + 1 から開始)。main は書かないでください。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。