티스토리 뷰
반응형
1) 목표
- do~while 문 이해하기
- continue, break 문 이해하기
2) 설명
do {
실행문1;
실행문2;
while (조건);
▶ for,while문과 같은 반복문입니다.
while문과의 차이는 while문 처럼 먼저 조건을 확인하고 참이면 실행문을 실행을 하느냐,
do~while 처럼 무조건 실행문을 실행하고 조건을 확인 하느냐의 차이입니다.
do~while문의 실행문은 반드시 1번은 조건에 상관없이 실행됩니다.
3-1) 예제프로그램
▶ vi do_while.c
#include <stdio.h>
int main() {
int i = 0;
do {
printf("i=[%d]\n", i+1);
i++;
} while (i < 10);
return 0;
}
▶ 컴파일/실행
~/c-lecture (master ✘)✖✹✭ ᐅ gcc -o do_while do_while.c
~/c-lecture (master ✘)✖✹✭ ᐅ ./do_while
i=[1]
i=[2]
i=[3]
i=[4]
i=[5]
i=[6]
i=[7]
i=[8]
i=[9]
i=[10]
~/c-lecture (master ✘)✖✹✭ ᐅ
▶ 분석
...
do {
printf("i=[%d]\n", i+1);
i++;
} while (i < 10);
- while문의 예제를 do~while문으로 대체한 예제입니다.
3-2) break 문
▶ vi do_while2.c
#include <stdio.h>
int main() {
int i = 0;
do {
printf("i=[%d]\n", i+1);
// break문
if (i == 2) {
break;
}
i++;
} while (i < 10);
return 0;
}
▶ 컴파일/실행
~/c-lecture (master ✘)✖✹✭ ᐅ gcc -o do_while2 do_while2.c
~/c-lecture (master ✘)✖✹✭ ᐅ ./do_while2
i=[1]
i=[2]
i=[3]
~/c-lecture (master ✘)✖✹✭ ᐅ
▶ 분석
- while문의 break문예제를 do~while문의 break문으로 대체한 예제입니다.
do~while에서도 break문을 만나면 반복이 중지됩니다.
3-3) continue 문
▶ vi do_while3.c
#include <stdio.h>
int main() {
int i = 0;
do {
// continue문
if (i % 2) {
i++;
continue;
}
printf("i=[%d]\n", i+1);
i++;
} while (i < 10);
return 0;
}
▶ 컴파일/실행
~/c-lecture (master ✘)✖✹✭ ᐅ gcc -o do_while3 do_while3.c
~/c-lecture (master ✘)✖✹✭ ᐅ ./do_while3
i=[1]
i=[3]
i=[5]
i=[7]
i=[9]
~/c-lecture (master ✘)✖✹✭ ᐅ
▶ 분석
- while문의 continue문예제를 do~while문의 continue문으로 대체한 예제입니다.
do~while에서도 continue문을 만나면 do 문으로 되돌아 갑니다.
※ 필자는 do~while문 보다 while문을 주로 많이 사용하고 있습니다.
반응형
'리눅스 C-언어 초급과정' 카테고리의 다른 글
| 11. 다차원 배열 (0) | 2022.11.16 |
|---|---|
| 10. 배열 (0) | 2022.11.16 |
| 8. while문 (0) | 2022.11.15 |
| 7. for문 (0) | 2022.11.14 |
| 6. switch ~ case문 (0) | 2022.11.14 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- GCC
- 전처리기
- #include
- 배열
- Pointer
- 소켓
- Call-By-Reference
- 리눅스
- 재고
- C언어
- c프로그램
- Clang
- Linux
- strcpy
- Member
- #ifdef
- String
- IPC
- 문자열
- 파라메타
- memcpy
- 의유
- #define
- struct
- 포인터
- While
- memset
- Call-by-value
- sharetravelplan
- array
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
글 보관함
