1 / 36

C 프로그래밍

C 프로그래밍 . 7 장 . 김 영 균 ygkim@cespc1.kumoh.ac.kr. 강의 내용. 7. 분기 (Branch) 와 점프 (Jump) • if, else 문 • switch 문 • continue 문 • break,case,default,goto 문 . - 교재 pp234. 예제 7.1  하루 중 최저 기온을 섭씨 온도로 읽어 들이고 입력된 총 항목 수와 영하의 기온을 기록한 백분율을 출력하는 프로그램 .

arleen
Download Presentation

C 프로그래밍

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C 프로그래밍 7장 김 영 균 ygkim@cespc1.kumoh.ac.kr

  2. 강의 내용 7. 분기(Branch)와 점프(Jump) • if, else문 • switch문 • continue문 • break,case,default,goto문

  3. - 교재 pp234. 예제 7.1  하루 중 최저 기온을 섭씨 온도로 읽어 들이고 입력된 총 항목 수와 영하의 기온을 기록한 백분율을 출력하는 프로그램. /* coldday.c -- 하루 중 영하로 내려간 비율 */ #include <stdio.h> #define SCALE “Celsius” #define FREEZING 0 int main(void) { float temperature; int freezing = 0; int days = 0; printf(“Enter the list of daily low temperatures. \n”); printf(“Use %s, and enter q to quit. \n”, SCALE);

  4. while(scanf(“%f”, &temperature) == 1 ) { days++; if(temperature < FREEZING ) freezing++; } if(days != 0) printf(“%d days total:%.1f%% were below freezing. \n”, days, 100.0 * (float) freezing / days); if(days==0) printf(“No data entered! \n”); return 0; /* 성공적으로 프로그램을 끝냄 */ }

  5. Enter the list of daily low temperatures. Use Celsius, and enter q to quit. 20 11 3 -4 -6 -10 -2.5 10 8 -5 q 10 days total: 50.0% were below freezing. - if문의 형식 if(expression) statement; - statement는 단일문 이거나 단일 블록이나 복합문이 될 수 있음. - if문에서는 조건이 맞으면 statement의 실행이 한번만 이루어 짐. - if문의 한가지 동작을 처리할 것인지 말 것인지를 선택. if else문은 두 가지 동작 중 한 가지 동작을 선택 할 수 있게 함.

  6. - if문에 else의 추가 if(days != 0) printf(“%d days total: %.1f%% were below freezing.\n”, days, 100.0 * (float) freezing / days); if(days==0) printf(“No data entered!\n”); 아래와 같이 else를 사용해서 다시 작성할 수 있음. if(days!=0) printf(“%d days total: %.1f%% were below freezing. \n”, days, 100.0 * (float) freezing /days); else printf(“No data entered!\n”);

  7. - if else문의 일반적 형식 if(expression) statement1 else statement2 만약 expression이 참이면(0이 아니면), statement1이 실행됨, 거짓 또는 0이면 else다음에 위치한 statement2가 실행 됨. - 복합문을 사용 할 경우 if (x>0) { printf(“Increment x:\n”); x++; } else printf(“x <= 0 \n”);

  8. - getchar()함수 getchar()함수는 인수 없이 사용하고 입력된 문자를 리턴 함. 입력 문자를 읽어 들여서 변수 ch에 그 값을 대입. ch = getchar(); 는 scanf(“%c”, &ch); 와 같다. - putchar()함수 인수로 주어지는 문자 값을 출력 한다. putchar(ch); 는 printf(“%c”,ch); 와 같다.

  9. - 교재 pp 240, 예제 7.2 /* cypher.c -- 입력과 출력 예제 */ #include <stdio.h> #define SPACE ‘ ‘ /* 따옴표-공백-따옴표 */ int main(void) { char ch; ch = getchar(); /* 문자 입력 */ while( ch != ‘\n’ ) /* 줄의 끝이 아닌 동안 반복 */ { if ( ch == SPACE ) /* 공백은 공백으로 출력 */ putchar(ch); else putchar(ch+1); /* 다른 문자인 경우 다음 문자를 출력 */ ch = getchar(); } return 0; }

  10. - 교재 pp 241, 예제 7.2 /* cypher2.c -- 입력과 출력 예제 */ #include <stdio.h> #define SPACE ‘ ‘ /* 따옴표-공백-따옴표 */ int main(void) { char ch; while(( ch=getchar() ) !=‘\n’ ) { if(ch==SPACE) /* 공백으로 공백으로 출력 */ putchar(ch); else putchar(ch+1); /* 다른 문자인 경우 다음 문자를 출력 */ } return 0; }

  11. - 교재 pp 242, 예제 7.4 전력회사는 고객이 사용하는 에너지의 양에 따라서 요금을 부과. 어떤 전력회사가 다음과 같이 요금을 부과. 처음 240kwh까지 : kwh당 $0.06898 다음 300kwh까지 : kwh당 $0.12032 다음 540kwh까지 : kwh당 $0.14022 /* electric.c -- 전기 요금 계산 */ #include <stdio.h> #define RATE1 0.06898 /* 처음 240kwh까지 요금 */ #define RATE2 0.12032 /* 다음 300kwh까지 요금 */ #define RATE3 0.14022 /* 다음 540kwh까지 요금 */ #define BREAK1 240.0 /* 요금의 첫번째 분기점 */ #define BREAK2 540.0 /* 요금의 두번째 분기점 */ #define BASE1 (RATE1 * BREAK1) #define BASE2 (BASE1 + (RATE2 * (BREAK2 - BREAK1)))

  12. - 교재 pp 242, 예제 7.4 int main(void) { float kwh; /* 사용한 전력량 */ float bill; /* 요금 */ printf(“Please enter the kwh used. \n”); scanf(“%f”, &kwh); if(kwh <= BREAK1) bill = RATE1 * kwh; else if (kwh <= BREAK2) /* 240에서 540kwh처리 */ bill = BASE1 + (RATE2 *(kwh-BREAK1)); else bill = BASE2 + (RATE3 *(kwh-BREAK2)); printf(“The charge for %.1f kwh is $%1.2f. \n”, kwh, bill); return 0; }

  13. - else와 if의 짝짓기 if( number > 6) if( number < 12 ) printf(“You’ re close! \n”); else printf(“Sorry, you lose a turn! \n”); - else는 가장 근접한 if와 짝을 이룬다. else가 첫번째 if의 짝이라면, if( number > 6) { if( number < 12 ) printf(“You’ re close! \n”); } else printf(“Sorry, you lose a turn! \n”);

  14. - 교재 pp249, 예제 7.5 /* divisors.c -- 중첩된 if문을 사용해서 수의 약수를 출력 */ #include <stdio.h> #define NO 0 #define YES 1 int main(void) { long num; long div; int prime; printf(“Please enter an integer for analysis; “); printf(“Enter q to quit. \n”); while( scanf(“%ld”, &num) ==1) { for(div =2 , prime = YES; (div*div) < = num; div++) {

  15. - 교재 pp249, 예제 7.5 if( num % div ==0 ) { if((div * div) != num) printf(“%ld is divisible by %ld and %ld. \n”, num, div, num / div ); else printf(“%ld is divisible by %ld. \n”, num,div); prime = NO; } } if (prime == YES) printf(“%ld is prime. \n”, num ); printf(“Please enter another integer for analysis; “); printf(“Enter q to quit. \n”); } return 0; }

  16. - if문을 사용하는 형태들 형식1 if ( expression ) statement expression이 참일 때, statement가 실행 된다. 형식2 if ( expression ) statement 1 else statement 2 만약 expression이 참이면, statement 1이 실행되고, 그렇지 않을 경우엔 statement 2가 실행 된다.

  17. - if문을 사용하는 형태들 형식3 if ( expression 1 ) statement 1 else if ( expression 2) statement 2 else statement 3 expression 1이 참이면, statement 1이 실행되고, 거짓이면, expression2가 참이면 statement 2가 실행되고, 두 수식이 모두 거짓일 때 statement 3이 실행 된다.

  18. - 교재 pp252, 예제 7.6 /* chcount.c -- 비 여백 문자의 수를 세는 프로그램 */ #include <stdio.h> #define PERIOD ‘.’ int main(void) { int ch; int charcount =0; while (( ch=getchar()) != PERIOD ) { if( ch != ‘ ‘ && ch != ‘\n’ && ch != ‘\t’ ) charcount++; } printf(“There are %d nonwhitespace characters. \n”, charcount ); }

  19. - C언어의 논리 연산자(logical operator) 연산자 의 미 && AND || OR ! NOT 1. exp1 && exp2 는 exp1과 exp2가 모두 참일 때만 참이다. 2. exp1 || exp2 는 exp1이나 exp2 중 어느 하나가 참이거나 둘 다 참일 때만 참이다. 3. !exp1은 exp1이 참이면 거짓이고 거짓이면 참이다.

  20. - 예를 들면, 5 > 2 && 4 > 7 은 거짓. 5 > 2 || 4 > 7 은 참. !( 4 > 7 ) 은 참. 왜냐하면, 4 > 7이 거짓이기 때문. - 연산 우선 순위 a > b && b > c || b > d 는 (( a > b) && ( b > c ) || ( b > d ) 로 해석 됨.

  21. - 단어 계수 프로그램 만들기(교재 pp. 255) 의사코드(pseudo code) read a character while there is more input increment character count if a line has been read, increment line count if a word has been read, increment word count read next character

  22. - 교재 pp. 257, 예제 7.7 /* wordcnt.c -- 문자, 단어, 라인 수 카운트 */ #include <stdio.h> #define STOP ‘|’ #define YES 1 #define NO 0 int main(void) { char c; /* 문자가 저장될 변수 */ long n_chars = 0L; /* 문자 수 */ int n_lines = 0; /* 라인 수 */ int n_words = 0; /* 단어 수 */ int wordflag = NO; /* c가 단어 안에 있으면 YES */ while (( c=getchar()) != STOP ) {

  23. n_chars++; /* 문자 수 카운트 */ if ( c == ‘\n’ ) n_lines++; /* 라인 수 카운트 */ if ( c != ‘ ‘ && c != ‘\n’ && c !=’\t’ && wordflag == NO ) { word_flag = YES; /* 새 단어 시작 */ n_words++; /* 단어 카운트 */ } if (( c==‘ ‘ || c==‘\n’ || c==‘\t’ ) && wordflag == YES ) wordflag = NO; /* 단어 끝에 도달 */ } printf(“ characters = %ld, words = %d, lines = %d\n”, n_chars, n_words, n_lines ); return 0; }

  24. - 조건 연산자 : ? : if else문의 형태를 갖는 간단한 연산자. 조건 연산자는 ? : 로 구성되어 있고, 3개의 피연산자를 갖는다. x = ( y < 0 ) ? -y : y ; 위의 조건 연산자는 다음의 if문과 동일하다. if ( y < 0 ) x = -y; else x = y; 조건 연산자의 일반적인 형태는 expression1 ? expression 2 : expression 3;

  25. - 교재 pp259, 예제 7.8 페인트 프로그램은 주어진 수의 평방 피트를 페인트 칠하기 위해서 얼마나 많은 페인트 통이 필요하게 되는 지를 계산 한다. 한 통으로 칠할 수 있는 평방 피트로 주어진 평방 피트를 나눈다. 답이 1.7통(can)인 경우, 페인트 가게는 통 단위로 판매 하므로, 올림(round up)을 해야 한다.

  26. - 교재 pp. 259 , 예제 7.8 /* paint.c -- 조건 연산자 사용 예 */ #include <stdio.h> #define COVERAGE 200 /* 페인트 한 통당 평방 피트 */ int main(void) { int sq_feet; int cans; printf(“Enter number of square feet to be painted:\n”); while (scanf(“%d”, &sq_feet) == 1 ) { cans = sq_feet / COVERAGE; cans += (( sq_feet % COVERAGE == 0)) ? 0 : 1; printf(“You need %d %s of paint. \n”, cans, cans == 1 ? “can” : “cans” ); } return 0; }

  27. - continue와 break문 루프(loop)의 본체에서 이루어지는 조건 검사에 따라 루프의 일부를 건너 뛰게 하거나 아니면 루프를 종결 시킬 수 있다. - continue문 다음 루프를 실행하도록 루프의 나머지 부분을 건너 뛰고, 프로그램의 순서를 조건 검사 부분으로 옮겨 가도록 함. 만약 continue문이 중첩된 루프 구조 속에 있게 되면 그것을 포함하는 내부 루프 구조에만 영향을 줌. /* skip.c -- continue를 이용해서 루프의 남은 부분을 건너 뜀 */ #include <stdio.h> #define MIN 0.0 #define MAX 100.0 int main(void) { float score; float total = 0.0;

  28. int n; float min = MAX; float max = MIN; printf(“Enter the scores:\n”); while ( scanf(“%f”, &score ) == 1) { if ( score < MIN || score > MAX ) { printf(“%0.1f is an invalid value.\n”, score); continue; } printf(“Accepting %0.1f:\n”, score); min = ( score < min ) ? score : min; max = ( score > max ) ? score : max; total += score; n++; }

  29. if ( n > 0 ) { printf(“Average of %d scores is %0.1f. \n”, n , total / n ); printf(“Low = %0.1f, high = %0.1f \n”, min, max); } else printf(“No valid scores were entered. \n”); return 0; }

  30. - break문 루프 내부에서 break문은 break를 감싸고 있는 루프로부터 벗어나게 해서 프로그램의 다음 단계로 진행하도록 함. - 교재 pp. 265 예제 7.10 /* break.c -- break를 이용해서 루프에서 빠져나가는 예 */ #include <stdio.h> int main(void) { float length, width; printf(“Enter the length of the rectangle: \n”); while( scanf(“%f”, &length ) == 1 ) { printf(“Length = %0.2f : \n”, length); printf(“Enter its width: \n”); if ( scanf(“%f”, &width ) != 1) break;

  31. printf(“Width = %0.2f:\n”, width); printf(“Area = %0.2f:\n”, length * width ); printf(“Enter the length of the rectangle:\n”); } return 0; }

  32. - 7.7 다중 선택 : switch와 break - 조건 연산자와 if else구조는 두개의 선택 중에서 하나를 선택해야 하는 프로그램을 작성하기 쉽도록 해 줌. - 여러 가지 선택 중 하나를 선택할 경우, switch문이 더 편리. - 교재 pp. 266, 예제 7.11 /* animals.c ---> switch문 사용 예 */ #include <stdio.h> int main(void) { char ch;

  33. printf(“Give me a letter of the alphabet, and i will give”); printf(“an animal name\n beginning with that letter. \n”); printf(“Please type in a letter: type a # to end my act. \n”); while( ( ch=getchar() != ‘#’ ) { if ( ch >= ‘a’ && ch <=‘z’ ) switch(ch) { case ‘a’ : printf(“argali, a wild sheep of Asia \n”); break;

  34. case ‘b’ : printf(“babirusa, a wild pig of Malay\n”); break; case ‘c’ : printf(“coati, racoonlike mammal\n”); break; case ‘d’: printf(“desman, aquatic, molelike critter\n”); break; case ‘e’: printf(“echidna, the spiny anteater \n”); break; default : printf(“That’s a stumper! \n”); } /* switch 문 끝 */

  35. else printf(“babirusa, a wild pig of Malay\n”); while ( getchar() != ‘\n’ ) continue; /* 입력 라인에 남은 내용 건너 뜀 */ printf(“Please type another letter or a #. \n”); } /* while 루프의 끝 */ printf(“Bye! \n”); return 0; }

  36. - switch단어 뒤의 괄호 속에 있는 수식을 평가. 그 평가된 값과 레이블(lable) 목록을 탐색(scan), 일치하는 값이 있는지를 알아 봄. 만약 일치하는 값이 있으면, 그 레이블로 프로그램의 제어가 이동. switch(number) { case 1: statement 1; break; case 2: statement 2; break; case 3: statement 3; break; default: statement 4; } statement 5;

More Related