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번 줄에 * 하나, 2번 줄에 둘, ..., 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. · 출력을 보려면 '실행'을 클릭하세요.