SlideShare uma empresa Scribd logo
1 de 31
2009년 1학기 프로그래밍 및 실습Chap. 4-3 조건문 (while & do~while) Bo-Kug Seo (sbk8941@mms.ssu.ac.kr) Soongsil Univ. MMS Lab.
이 장에서 다룰 내용 while문 do ~ while문 기타 제어문
while 문 while 문의 실행 순서 조건식이 참인 동안 반복할 문장 수행 중괄호가 끝나는 곳에서 조건식으로 돌아와 같은 동작 반복
while 문 for 문과 while 문의 사용 형식 비교 0~9까지 출력하는 예 int i; for(i=0; i<10; i++) { 	printf(“%d ”, i); }  초기값을 for 문 밖으로 이동  증감식을 for 문의 끝으로 이동 for를 while로  int i; i = 0; while(i<10) { 	printf(“%d ”, i); 	i++; }
[기본예제 4-19] for 문을 while 문으로 바꾸기 01 #include <stdio.h> 02 03 int main() 04 { 05 		int i; 06 		i=0; 07 08 		while ( i < 5 ){ 09 			printf("while 문을 공부합니다."); 10 			i++; 11 		} 12 } 초기값 지정 조건식 증감식
while 문 for 문을 while 문으로 변환하는 방법
[기본예제 4-20] for 문을 while 문으로 바꾸기 01 #include <stdio.h> 02 03 int main() 04 { 05 		int hap=0; 06 		int i; 07 08		[  ①  ] 09 		while ( i<=10 ) { 10 			hap = hap + i; 11			[  ②  ] 12 		} 13 14 		printf(" 1에서 10까지의 합: %d ", hap); 15 } i = 1; 초기값 지정 조건식 i ++; 증감식
while 문 무한루프를 위한 while 문 조건식이 무조건 참이어야 함 for( ; ; )와 동일한 역할 while(1) 로 표현
[기본예제 4-21] while 문의 무한루프 만들기 무한루프 입력 값을 공백으로 분리 출력 01 #include <stdio.h> 02 03 int main() 04 { 05 		int a, b; 06 07 		while ( 1 ) 08 		{ 09 			printf ("더할 두 수 입력 (멈추려면 Ctrl+C) : ") ; 10 			scanf("%d %d", &a, &b); 11 12 			printf("%d + %d = %d ", a, b, a+b); 13 		} 14 }
[응용예제] 무한루프를 활용한 계산기 -1 01 #include <stdio.h> 02 03 int main() 04 { 05 		int a, b; 06 		char ch; 07 08 		[    ①    ] 09 		{ 10 			printf ("계산할 두 수를 입력 (멈추려면 Ctrl+C) : ") ; 11 			scanf("%d %d", &a, &b); 12 13 			printf("계산할 연산자를 입력하세요 : "); 14 			scanf("%*c%c", &ch); 15 16 		[   ②   ](ch) 17 		{ while(1) 무한루프 키보드로 숫자 2개를 입력받음 연산자 입력 switch
[응용예제] 무한루프를 활용한 계산기 -2 18 			case '+' : 19 				printf("%d + %d = %d 입니다. ", a, b, a+b); 20 				break; 21 			case '-' : 22 				printf("%d - %d = %d 입니다. ", a, b, a-b); 23 				break; 24 			case '*' : 25 				printf("%d * %d = %d 입니다. ", a, b, a*b); 26 				break; 27 			case '/' : 28 				printf("%d / %d = %f 입니다. ", a, b, a/(float)b); 29 				break; 30 			case '%' : 31 				printf("%d %% %d = %d 입니다. ", a, b, a%b); 32 				break;
[응용예제] 무한루프를 활용한 계산기 -3 33 			default : 34 				printf("연산자를 잘못 입력했습니다. "); 35 			} 36 		} 37 }
do~while 문 do~while 문 조건식을 확인하기 전에 ‘반복할 문장’을 수행  무조건 한 번은 실행됨 형식은 while 문과 동일하지만, 조건식이 아래에 위치
[기본예제 4-22] do~while 문의 사용 예 01 #include <stdio.h> 02 03 int main() 04 { 05 		int a = 100; 06 07 		while ( a == 200 ) 08 		{ 09 			printf ("while 문 내부에 들어 왔습니다.") ; 10 		} 11 12 		do { 13 			printf ("do ~ while 문 내부에 들어 왔습니다.") ; 14 		} while ( a == 200 ) ; 15 } while 문 실행 :  조건식 먼저 판단 do~while 문 실행 :먼저 실행한 후에 조건식 판단
[응용예제] do~while 문의 사용 예 -1 01 #include <stdio.h> 02 03 int main() 04 { 05 		int menu; 06 07 		[ ① ]{ 08 			printf("손님 주문하시겠습니까 ? "); 09 			printf("<1> 스테이크 <2> 스파게티 <3> 물 "); 10 			printf("<4> 빵 <5> 그만 시킬래요 ==> "); 11 			scanf("%d", &menu); 12 13 			switch(menu) 14 			{ 15 				case 1 : printf("#스테이크 알겠습니다."); break; do 문이므로 한번은 꼭 수행 do 메뉴 출력 메뉴 선택 선택한 메뉴에 따라 주문을 접수
[응용예제] do~while 문의 사용 예 -2 16 				case 2 : printf("#스파게티 알겠습니다."); break; 17 				case 3 : printf("#물 알겠습니다."); break; 18 				case 4 : printf("#빵 알겠습니다."); break; 19 				case 5 : printf("안녕히 가세요."); break; 20 				default : printf("잘못 주문하셨습니다."); 21 			} 22 		} [  ②  ](menu != 5); 23 } [위의 응용예제] 선택한 메뉴가 5가 아닌 동안 계속 수행 while
기타 제어문 break 문 for, while, do~while과 같은 반복문을 탈출할 때 사용 if 문과 결합하여 무한루프 안에 사용 무한루프를 돌다 특정 조건을 만족하면 프로그램을 종료하는 역할
[기본예제 4-23] break 문의 사용 예  01 #include <stdio.h> 02 03 int main() 04 { 05 		int i; 06 07 		for( i=1 ; i<=100 ; i++) 08 		{ 09 			printf("for 문을 %d 회 실행했습니다.", i); 10 			break; 11 		} 12 13 		printf("for 문을 종료했습니다."); 14 } 100번 반복 출력 무조건 for 문을 빠져나감
[기본예제 4-24] break 문의사용 예  01 #include <stdio.h> 02 03 int main() 04 { 05 		int a, b; 06 07 		while ( 1 ) 08 		{ 09 			printf ("더할 두 수 입력(멈추려면 0을 입력) : ") ; 10 			scanf("%d %d", &a, &b); 11 12 			if (a == 0) 13 				break; 14 15 			printf("%d + %d = %d ", a, b, a+b); 16 		} 무한 루프 키보드로 숫자 두 개를 입력받음 입력값이 0이면 무조건 for 문을 빠져나감
[기본예제 4-24] break 문의사용 예 17 18 			printf("0을 입력해서 for 문을 탈출했습니다."); 19 }
[기본예제 4-25] break 문의 사용 예  01 #include <stdio.h> 02 03 int main() 04 { 05 		int i; 06 		i = 0; 07 		for ( ; ; ) 08 		{ 09 			printf (" %d ", i) ; 10 			i ++ ; 11 			if (i < 10) 12 			{ break; } 13 		} 14 15 } 무한루프 i 값 출력 후 1을 더해줌 i 가 10보다 작으면 반복문의 블록을 무조건 빠져나감
기타 제어문 break 문의 탈출 범위 현재 실행중인 반복문 블록을 무조건 빠져나오는 명령문 [기본예제 7-9]의 수정 i 값이 0부터 시작하므로 첫번째 루프를 돌 때 프로그램 종료 1~9까지 출력하려면 부등호를 수정해야 함 for( ; ; ) {   ... 	if(i < 10) 	{ break; } } ??
[응용예제] break 문의 사용 예 01 #include <stdio.h> 02 03 int main() 04 { 05 		int hap = 0; 06 		int i; 07 08 		for ( i=1 ; i<=100 ; i++) 09 		{ 10 			hap = hap + i; 11 12 			if (hap>=100) 13 				break; 14 		} 15 16 		printf(" 1~100의 합에서 최초로 1000이 넘는 위치는? : %d", i); 17 } 100번 반복 실행 i 값을 hap에 누적 hap이 100보다 크거나 같으면 블록을 빠져나감 블록을 빠져나간 순간의 i 값
기타 제어문 블록의 끝으로 가는 continue 문 블록의 끝으로 이동한 후 반복문을 처음부터 다시 수행
[기본예제 4-26] continue 문의 사용 예 01 #include <stdio.h> 02 03 int main() 04 { 05 		int hap = 0; 06 		int i; 07 08 		for ( i=1 ; i<=100 ; i++ ) 09 		{ 10 			if ( i % 3 == 0 ) 11 			continue; 12 13 			hap += i; 14 		} 15 16 		printf(" 1~100까지의 합(3의 배수 제외): %d", hap); 17 } 1부터 100까지 반복 나머지 값이 0일 때(3의 배수) 블록의 끝으로 이동 3의 배수가 아닌 i 값 누적 누적된 값 출력
기타 제어문 지정한 위치로 이동하는 goto 문 지정된 레이블(label)로 건너뛰게 하는 명령문 프로그램의 흐름을 복잡하게 만드는 단점이 있음
[기본예제 4-27] goto 문의 사용 예 01 #include <stdio.h> 02 03 int main() 04 { 05 		int hap = 0; 06 		int i; 07 08 		for( i=1 ; i<=100 ; i++) 09 		{ 10 			hap += i; 11 12 		if (hap > 2000) 13 			goto mygoto; 14 		} 15 16 		mygoto : 17 			printf ("1부터 %d까지 합하면 2000이 넘어요.", i); 18 } 1부터 100까지 반복 합계 누적 누적된 값이 2000이 넘으면 mygoto로 무조건 이동 mygoto 레이블
기타 제어문 호출한 곳으로 돌아가는 return 문 현재 실행중인 함수를 끝내고, 해당 함수를 호출한 곳으로 돌아가게 함 return 문을 만나면 프로그램이 종료되는 효과
[기본예제 4-28] return 문의 사용 예 01 #include <stdio.h> 02 03 int main() 04 { 05 		int hap = 0; 06 		int i; 07 08 		for( i=1 ; i<=100 ; i++) 09 		hap += i; 10 11 		printf("1부터 100까지의 합은 %d 입니다.", hap); 12 		return 0; 13 14 		printf("프로그램의 끝입니다."); 15 } 1부터 100까지 반복 합계 누적 출력 현재 함수를 호출한 곳으로 복귀 한 번도 출력되지 않음
[예제모음 1] 원하는 배수의 합계를 구하는 계산기 예제설명 입력한 두 수 사이의 합계를 구하되, 원하는 배수를 선택하여 합계를 구하는 프로그램이다. ,[object Object],실행결과
요약 for 문과 같이 특정 동작의 반복을 위해 사용 while 문의 형식 while 문 while ( 초기값) { 	반복할 문장들; } while 문과 거의 동일하지만, 조건과 상관없이 무조건 반복할 문장을 한 번은 수행 do~while 문의 형식 do ~ while 문 do { 반복할 문장들; } while (조건식); break 문 : 현재의 반복문을 무조건 탈출 continue 문 : 무조건 블록의 끝으로 이동한 후 다시 반복문의 처음으로 돌아감 return 문 : 현재 함수를 호출한 곳으로 돌아감. ,[object Object],기타 제어문

Mais conteúdo relacionado

Mais procurados

[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...Seok-joon Yun
 
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
[C++ Korea] Effective Modern C++ Study item14 16 +신촌[C++ Korea] Effective Modern C++ Study item14 16 +신촌
[C++ Korea] Effective Modern C++ Study item14 16 +신촌Seok-joon Yun
 
C++ 타입 추론
C++ 타입 추론C++ 타입 추론
C++ 타입 추론Huey Park
 
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...Seok-joon Yun
 
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준Seok-joon Yun
 
[방송통신대 컴퓨터과학과] C++ 프로그래밍 과제물 작성
[방송통신대 컴퓨터과학과] C++ 프로그래밍 과제물 작성[방송통신대 컴퓨터과학과] C++ 프로그래밍 과제물 작성
[방송통신대 컴퓨터과학과] C++ 프로그래밍 과제물 작성Lee Sang-Ho
 
C++17 Key Features Summary - Ver 2
C++17 Key Features Summary - Ver 2C++17 Key Features Summary - Ver 2
C++17 Key Features Summary - Ver 2Chris Ohk
 
[방송통신대 컴퓨터과학과] C 프로그래밍 과제물 작성
[방송통신대 컴퓨터과학과] C 프로그래밍 과제물 작성[방송통신대 컴퓨터과학과] C 프로그래밍 과제물 작성
[방송통신대 컴퓨터과학과] C 프로그래밍 과제물 작성Lee Sang-Ho
 
Visual studio 2010
Visual studio 2010Visual studio 2010
Visual studio 2010MinGeun Park
 
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...Seok-joon Yun
 
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23Seok-joon Yun
 
[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features Summary[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features SummaryChris Ohk
 
프로그래밍 및 실습 Chap2
프로그래밍 및 실습 Chap2프로그래밍 및 실습 Chap2
프로그래밍 및 실습 Chap2dktm
 
Pure Function and Rx
Pure Function and RxPure Function and Rx
Pure Function and RxHyungho Ko
 
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...Seok-joon Yun
 
C수업자료
C수업자료C수업자료
C수업자료koominsu
 
[KOSSA] C++ Programming - 13th Study - exception handling
[KOSSA] C++ Programming - 13th Study - exception handling[KOSSA] C++ Programming - 13th Study - exception handling
[KOSSA] C++ Programming - 13th Study - exception handlingSeok-joon Yun
 
게임프로그래밍입문 3주차
게임프로그래밍입문 3주차게임프로그래밍입문 3주차
게임프로그래밍입문 3주차Yeonah Ki
 
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...
[C++ korea] effective modern c++ study   item 2 understanding auto type deduc...[C++ korea] effective modern c++ study   item 2 understanding auto type deduc...
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...Seok-joon Yun
 

Mais procurados (20)

[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
[C++ Korea] Effective Modern C++ MVA item 9 Prefer alias declarations to type...
 
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
[C++ Korea] Effective Modern C++ Study item14 16 +신촌[C++ Korea] Effective Modern C++ Study item14 16 +신촌
[C++ Korea] Effective Modern C++ Study item14 16 +신촌
 
C++ 타입 추론
C++ 타입 추론C++ 타입 추론
C++ 타입 추론
 
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
[C++ Korea] Effective Modern C++ mva item 7 distinguish between and {} when c...
 
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
[C++ Korea] Effective Modern C++ MVA item 8 Prefer nullptr to 0 and null +윤석준
 
[방송통신대 컴퓨터과학과] C++ 프로그래밍 과제물 작성
[방송통신대 컴퓨터과학과] C++ 프로그래밍 과제물 작성[방송통신대 컴퓨터과학과] C++ 프로그래밍 과제물 작성
[방송통신대 컴퓨터과학과] C++ 프로그래밍 과제물 작성
 
C++17 Key Features Summary - Ver 2
C++17 Key Features Summary - Ver 2C++17 Key Features Summary - Ver 2
C++17 Key Features Summary - Ver 2
 
[방송통신대 컴퓨터과학과] C 프로그래밍 과제물 작성
[방송통신대 컴퓨터과학과] C 프로그래밍 과제물 작성[방송통신대 컴퓨터과학과] C 프로그래밍 과제물 작성
[방송통신대 컴퓨터과학과] C 프로그래밍 과제물 작성
 
Visual studio 2010
Visual studio 2010Visual studio 2010
Visual studio 2010
 
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
Effective Modern C++ MVA item 18 Use std::unique_ptr for exclusive-ownership ...
 
C++11
C++11C++11
C++11
 
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
[C++ korea] Effective Modern C++ 신촌 Study Item20,21,23
 
[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features Summary[C++ Korea 2nd Seminar] C++17 Key Features Summary
[C++ Korea 2nd Seminar] C++17 Key Features Summary
 
프로그래밍 및 실습 Chap2
프로그래밍 및 실습 Chap2프로그래밍 및 실습 Chap2
프로그래밍 및 실습 Chap2
 
Pure Function and Rx
Pure Function and RxPure Function and Rx
Pure Function and Rx
 
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
[C++ korea] effective modern c++ study item 14 declare functions noexcept if ...
 
C수업자료
C수업자료C수업자료
C수업자료
 
[KOSSA] C++ Programming - 13th Study - exception handling
[KOSSA] C++ Programming - 13th Study - exception handling[KOSSA] C++ Programming - 13th Study - exception handling
[KOSSA] C++ Programming - 13th Study - exception handling
 
게임프로그래밍입문 3주차
게임프로그래밍입문 3주차게임프로그래밍입문 3주차
게임프로그래밍입문 3주차
 
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...
[C++ korea] effective modern c++ study   item 2 understanding auto type deduc...[C++ korea] effective modern c++ study   item 2 understanding auto type deduc...
[C++ korea] effective modern c++ study item 2 understanding auto type deduc...
 

Semelhante a (학생용)+프로그래밍+및+실습 Chap4 3

불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 명신 김
 
RNC C++ lecture_4 While, For
RNC C++ lecture_4 While, ForRNC C++ lecture_4 While, For
RNC C++ lecture_4 While, Foritlockit
 
C수업자료
C수업자료C수업자료
C수업자료koominsu
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types웅식 전
 
게임프로그래밍입문 5주차
게임프로그래밍입문 5주차게임프로그래밍입문 5주차
게임프로그래밍입문 5주차Yeonah Ki
 
C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부Gwangwhi Mah
 
14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿유석 남
 
C Language I
C Language IC Language I
C Language ISuho Kwon
 
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)Sang Don Kim
 
20150212 c++11 features used in crow
20150212 c++11 features used in crow20150212 c++11 features used in crow
20150212 c++11 features used in crowJaeseung Ha
 
포인터의기초 (2) - 포인터 사용하기1
포인터의기초 (2) - 포인터 사용하기1포인터의기초 (2) - 포인터 사용하기1
포인터의기초 (2) - 포인터 사용하기1Hoyoung Jung
 
게임프로그래밍입문 4주차
게임프로그래밍입문 4주차게임프로그래밍입문 4주차
게임프로그래밍입문 4주차Yeonah Ki
 
About Visual C++ 10
About  Visual C++ 10About  Visual C++ 10
About Visual C++ 10흥배 최
 
C Language For Arduino
C Language For ArduinoC Language For Arduino
C Language For Arduino영욱 김
 
Angular2를 위한 타입스크립트
Angular2를 위한 타입스크립트Angular2를 위한 타입스크립트
Angular2를 위한 타입스크립트Jin wook
 

Semelhante a (학생용)+프로그래밍+및+실습 Chap4 3 (20)

4. loop
4. loop4. loop
4. loop
 
불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14 불어오는 변화의 바람, From c++98 to c++11, 14
불어오는 변화의 바람, From c++98 to c++11, 14
 
HI-ARC PS 101
HI-ARC PS 101HI-ARC PS 101
HI-ARC PS 101
 
RNC C++ lecture_4 While, For
RNC C++ lecture_4 While, ForRNC C++ lecture_4 While, For
RNC C++ lecture_4 While, For
 
C수업자료
C수업자료C수업자료
C수업자료
 
C review
C  reviewC  review
C review
 
2 1. variables & data types
2 1. variables & data types2 1. variables & data types
2 1. variables & data types
 
게임프로그래밍입문 5주차
게임프로그래밍입문 5주차게임프로그래밍입문 5주차
게임프로그래밍입문 5주차
 
C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부C++ 11 에 대해서 쉽게 알아봅시다 1부
C++ 11 에 대해서 쉽게 알아봅시다 1부
 
14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿14장 - 15장 예외처리, 템플릿
14장 - 15장 예외처리, 템플릿
 
C Language I
C Language IC Language I
C Language I
 
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
[Td 2015]녹슨 c++ 코드에 모던 c++로 기름칠하기(옥찬호)
 
20150212 c++11 features used in crow
20150212 c++11 features used in crow20150212 c++11 features used in crow
20150212 c++11 features used in crow
 
포인터의기초 (2) - 포인터 사용하기1
포인터의기초 (2) - 포인터 사용하기1포인터의기초 (2) - 포인터 사용하기1
포인터의기초 (2) - 포인터 사용하기1
 
게임프로그래밍입문 4주차
게임프로그래밍입문 4주차게임프로그래밍입문 4주차
게임프로그래밍입문 4주차
 
About Visual C++ 10
About  Visual C++ 10About  Visual C++ 10
About Visual C++ 10
 
C Language For Arduino
C Language For ArduinoC Language For Arduino
C Language For Arduino
 
ch04
ch04ch04
ch04
 
3.포인터
3.포인터3.포인터
3.포인터
 
Angular2를 위한 타입스크립트
Angular2를 위한 타입스크립트Angular2를 위한 타입스크립트
Angular2를 위한 타입스크립트
 

(학생용)+프로그래밍+및+실습 Chap4 3

  • 1. 2009년 1학기 프로그래밍 및 실습Chap. 4-3 조건문 (while & do~while) Bo-Kug Seo (sbk8941@mms.ssu.ac.kr) Soongsil Univ. MMS Lab.
  • 2. 이 장에서 다룰 내용 while문 do ~ while문 기타 제어문
  • 3. while 문 while 문의 실행 순서 조건식이 참인 동안 반복할 문장 수행 중괄호가 끝나는 곳에서 조건식으로 돌아와 같은 동작 반복
  • 4. while 문 for 문과 while 문의 사용 형식 비교 0~9까지 출력하는 예 int i; for(i=0; i<10; i++) { printf(“%d ”, i); } 초기값을 for 문 밖으로 이동 증감식을 for 문의 끝으로 이동 for를 while로 int i; i = 0; while(i<10) { printf(“%d ”, i); i++; }
  • 5. [기본예제 4-19] for 문을 while 문으로 바꾸기 01 #include <stdio.h> 02 03 int main() 04 { 05 int i; 06 i=0; 07 08 while ( i < 5 ){ 09 printf("while 문을 공부합니다."); 10 i++; 11 } 12 } 초기값 지정 조건식 증감식
  • 6. while 문 for 문을 while 문으로 변환하는 방법
  • 7. [기본예제 4-20] for 문을 while 문으로 바꾸기 01 #include <stdio.h> 02 03 int main() 04 { 05 int hap=0; 06 int i; 07 08 [ ① ] 09 while ( i<=10 ) { 10 hap = hap + i; 11 [ ② ] 12 } 13 14 printf(" 1에서 10까지의 합: %d ", hap); 15 } i = 1; 초기값 지정 조건식 i ++; 증감식
  • 8. while 문 무한루프를 위한 while 문 조건식이 무조건 참이어야 함 for( ; ; )와 동일한 역할 while(1) 로 표현
  • 9. [기본예제 4-21] while 문의 무한루프 만들기 무한루프 입력 값을 공백으로 분리 출력 01 #include <stdio.h> 02 03 int main() 04 { 05 int a, b; 06 07 while ( 1 ) 08 { 09 printf ("더할 두 수 입력 (멈추려면 Ctrl+C) : ") ; 10 scanf("%d %d", &a, &b); 11 12 printf("%d + %d = %d ", a, b, a+b); 13 } 14 }
  • 10. [응용예제] 무한루프를 활용한 계산기 -1 01 #include <stdio.h> 02 03 int main() 04 { 05 int a, b; 06 char ch; 07 08 [ ① ] 09 { 10 printf ("계산할 두 수를 입력 (멈추려면 Ctrl+C) : ") ; 11 scanf("%d %d", &a, &b); 12 13 printf("계산할 연산자를 입력하세요 : "); 14 scanf("%*c%c", &ch); 15 16 [ ② ](ch) 17 { while(1) 무한루프 키보드로 숫자 2개를 입력받음 연산자 입력 switch
  • 11. [응용예제] 무한루프를 활용한 계산기 -2 18 case '+' : 19 printf("%d + %d = %d 입니다. ", a, b, a+b); 20 break; 21 case '-' : 22 printf("%d - %d = %d 입니다. ", a, b, a-b); 23 break; 24 case '*' : 25 printf("%d * %d = %d 입니다. ", a, b, a*b); 26 break; 27 case '/' : 28 printf("%d / %d = %f 입니다. ", a, b, a/(float)b); 29 break; 30 case '%' : 31 printf("%d %% %d = %d 입니다. ", a, b, a%b); 32 break;
  • 12. [응용예제] 무한루프를 활용한 계산기 -3 33 default : 34 printf("연산자를 잘못 입력했습니다. "); 35 } 36 } 37 }
  • 13. do~while 문 do~while 문 조건식을 확인하기 전에 ‘반복할 문장’을 수행  무조건 한 번은 실행됨 형식은 while 문과 동일하지만, 조건식이 아래에 위치
  • 14. [기본예제 4-22] do~while 문의 사용 예 01 #include <stdio.h> 02 03 int main() 04 { 05 int a = 100; 06 07 while ( a == 200 ) 08 { 09 printf ("while 문 내부에 들어 왔습니다.") ; 10 } 11 12 do { 13 printf ("do ~ while 문 내부에 들어 왔습니다.") ; 14 } while ( a == 200 ) ; 15 } while 문 실행 : 조건식 먼저 판단 do~while 문 실행 :먼저 실행한 후에 조건식 판단
  • 15. [응용예제] do~while 문의 사용 예 -1 01 #include <stdio.h> 02 03 int main() 04 { 05 int menu; 06 07 [ ① ]{ 08 printf("손님 주문하시겠습니까 ? "); 09 printf("<1> 스테이크 <2> 스파게티 <3> 물 "); 10 printf("<4> 빵 <5> 그만 시킬래요 ==> "); 11 scanf("%d", &menu); 12 13 switch(menu) 14 { 15 case 1 : printf("#스테이크 알겠습니다."); break; do 문이므로 한번은 꼭 수행 do 메뉴 출력 메뉴 선택 선택한 메뉴에 따라 주문을 접수
  • 16. [응용예제] do~while 문의 사용 예 -2 16 case 2 : printf("#스파게티 알겠습니다."); break; 17 case 3 : printf("#물 알겠습니다."); break; 18 case 4 : printf("#빵 알겠습니다."); break; 19 case 5 : printf("안녕히 가세요."); break; 20 default : printf("잘못 주문하셨습니다."); 21 } 22 } [ ② ](menu != 5); 23 } [위의 응용예제] 선택한 메뉴가 5가 아닌 동안 계속 수행 while
  • 17. 기타 제어문 break 문 for, while, do~while과 같은 반복문을 탈출할 때 사용 if 문과 결합하여 무한루프 안에 사용 무한루프를 돌다 특정 조건을 만족하면 프로그램을 종료하는 역할
  • 18. [기본예제 4-23] break 문의 사용 예 01 #include <stdio.h> 02 03 int main() 04 { 05 int i; 06 07 for( i=1 ; i<=100 ; i++) 08 { 09 printf("for 문을 %d 회 실행했습니다.", i); 10 break; 11 } 12 13 printf("for 문을 종료했습니다."); 14 } 100번 반복 출력 무조건 for 문을 빠져나감
  • 19. [기본예제 4-24] break 문의사용 예 01 #include <stdio.h> 02 03 int main() 04 { 05 int a, b; 06 07 while ( 1 ) 08 { 09 printf ("더할 두 수 입력(멈추려면 0을 입력) : ") ; 10 scanf("%d %d", &a, &b); 11 12 if (a == 0) 13 break; 14 15 printf("%d + %d = %d ", a, b, a+b); 16 } 무한 루프 키보드로 숫자 두 개를 입력받음 입력값이 0이면 무조건 for 문을 빠져나감
  • 20. [기본예제 4-24] break 문의사용 예 17 18 printf("0을 입력해서 for 문을 탈출했습니다."); 19 }
  • 21. [기본예제 4-25] break 문의 사용 예 01 #include <stdio.h> 02 03 int main() 04 { 05 int i; 06 i = 0; 07 for ( ; ; ) 08 { 09 printf (" %d ", i) ; 10 i ++ ; 11 if (i < 10) 12 { break; } 13 } 14 15 } 무한루프 i 값 출력 후 1을 더해줌 i 가 10보다 작으면 반복문의 블록을 무조건 빠져나감
  • 22. 기타 제어문 break 문의 탈출 범위 현재 실행중인 반복문 블록을 무조건 빠져나오는 명령문 [기본예제 7-9]의 수정 i 값이 0부터 시작하므로 첫번째 루프를 돌 때 프로그램 종료 1~9까지 출력하려면 부등호를 수정해야 함 for( ; ; ) { ... if(i < 10) { break; } } ??
  • 23. [응용예제] break 문의 사용 예 01 #include <stdio.h> 02 03 int main() 04 { 05 int hap = 0; 06 int i; 07 08 for ( i=1 ; i<=100 ; i++) 09 { 10 hap = hap + i; 11 12 if (hap>=100) 13 break; 14 } 15 16 printf(" 1~100의 합에서 최초로 1000이 넘는 위치는? : %d", i); 17 } 100번 반복 실행 i 값을 hap에 누적 hap이 100보다 크거나 같으면 블록을 빠져나감 블록을 빠져나간 순간의 i 값
  • 24. 기타 제어문 블록의 끝으로 가는 continue 문 블록의 끝으로 이동한 후 반복문을 처음부터 다시 수행
  • 25. [기본예제 4-26] continue 문의 사용 예 01 #include <stdio.h> 02 03 int main() 04 { 05 int hap = 0; 06 int i; 07 08 for ( i=1 ; i<=100 ; i++ ) 09 { 10 if ( i % 3 == 0 ) 11 continue; 12 13 hap += i; 14 } 15 16 printf(" 1~100까지의 합(3의 배수 제외): %d", hap); 17 } 1부터 100까지 반복 나머지 값이 0일 때(3의 배수) 블록의 끝으로 이동 3의 배수가 아닌 i 값 누적 누적된 값 출력
  • 26. 기타 제어문 지정한 위치로 이동하는 goto 문 지정된 레이블(label)로 건너뛰게 하는 명령문 프로그램의 흐름을 복잡하게 만드는 단점이 있음
  • 27. [기본예제 4-27] goto 문의 사용 예 01 #include <stdio.h> 02 03 int main() 04 { 05 int hap = 0; 06 int i; 07 08 for( i=1 ; i<=100 ; i++) 09 { 10 hap += i; 11 12 if (hap > 2000) 13 goto mygoto; 14 } 15 16 mygoto : 17 printf ("1부터 %d까지 합하면 2000이 넘어요.", i); 18 } 1부터 100까지 반복 합계 누적 누적된 값이 2000이 넘으면 mygoto로 무조건 이동 mygoto 레이블
  • 28. 기타 제어문 호출한 곳으로 돌아가는 return 문 현재 실행중인 함수를 끝내고, 해당 함수를 호출한 곳으로 돌아가게 함 return 문을 만나면 프로그램이 종료되는 효과
  • 29. [기본예제 4-28] return 문의 사용 예 01 #include <stdio.h> 02 03 int main() 04 { 05 int hap = 0; 06 int i; 07 08 for( i=1 ; i<=100 ; i++) 09 hap += i; 10 11 printf("1부터 100까지의 합은 %d 입니다.", hap); 12 return 0; 13 14 printf("프로그램의 끝입니다."); 15 } 1부터 100까지 반복 합계 누적 출력 현재 함수를 호출한 곳으로 복귀 한 번도 출력되지 않음
  • 30.
  • 31.