Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9a26882

Browse files
committed
➕ 반복문 활용법 추가
1 parent c0cb2d0 commit 9a26882

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

‎7-control-flow/README.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -933,4 +933,76 @@ Sum: 65
933933
934934
> `!i`에 주목해주세요. 부정 연산자는 참인 값을 거짓으로, 거짓인 값을 참으로 바꿔줍니다. 즉, `0`이 아닌 식은 `0`으로, `0`인 식은 `1`로 바꿔주는 연산자입니다. 그래서 `i``0`이 아니면 조건식의 결과값이 `0`이 되어 if문 안쪽이 실행되지 않고, `i``0`이면 조건식의 결과값이 `1`이 되어 if문 안쪽이 실행됩니다. 이렇게 사용자가 `0`을 입력하면 반복문을 종료하게 만들 수 있습니다.
935935
936+
## 반복문 활용하기
937+
938+
반복문들도 문장이기 때문에, 반복문 안에 반복문을 집어넣는 것도 가능합니다. 반복문끼리 겹쳐쓰는 대표적인 예시가 바로 구구단 출력인데요,
939+
940+
```c
941+
#include <stdio.h>
942+
943+
int main()
944+
{
945+
int row_num = 2;
946+
while (row_num <= 9)
947+
{
948+
for (int i = 1; i <= 9; ++i)
949+
printf("%d * %d = %d\n", row_num, i, row_num * i);
950+
++row_num;
951+
}
952+
}
953+
```
954+
```
955+
2 * 1 = 2
956+
2 * 2 = 4
957+
2 * 3 = 6
958+
2 * 4 = 8
959+
2 * 5 = 10
960+
2 * 6 = 12
961+
2 * 7 = 14
962+
2 * 8 = 16
963+
...
964+
9 * 3 = 27
965+
9 * 4 = 36
966+
9 * 5 = 45
967+
9 * 6 = 54
968+
9 * 7 = 63
969+
9 * 8 = 72
970+
9 * 9 = 81
971+
```
972+
973+
이렇게 순식간에 구구단을 계산하는 것을 확인할 수 있습니다. 반복문뿐만 아니라 조건문도 문장이기 때문에, 반복문 안에 조건문을 넣기도 하고, 조건문 안에 반복문을 넣기도 합니다. 다음 프로그램은 주어진 정수가 20000 이하일 때, 그 정수보다 작거나 같은 소수를 출력합니다.
974+
975+
```c
976+
#include <stdio.h>
977+
978+
int main()
979+
{
980+
int threshold; scanf("%d", &threshold);
981+
982+
if (threshold > 10000)
983+
printf("given number is too big");
984+
else
985+
for (int num = 2; num <= threshold; ++num)
986+
{
987+
int is_prime = 1;
988+
989+
for (int i = 2; i * i <= num; ++i)
990+
{
991+
if (num % i == 0) is_prime = 0;
992+
}
993+
994+
if (is_prime)
995+
printf("%d ", num);
996+
}
997+
}
998+
```
999+
```
1000+
: 100
1001+
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
1002+
```
1003+
```
1004+
: 20000
1005+
given number is too big
1006+
```
1007+
9361008
[다음: 함수](../8-functions)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /