C언어 4장

Download Report

Transcript C언어 4장

Chapter 4
단순 선택과 반복



Chapter 4
단순 선택 구조
제어 반복 구조
구조적 프로그래밍
문제해결을 위한 C언어 프로그래밍
1
제어 흐름(flow of control)이란?



Chapter 4
제어 흐름(Flow of Control)이란 프로그램에서 명령문들의 실행 순서를
말한다.
모든 프로그램은 다음 세 가지의 제어 흐름을 가진다:
1. 순차(Sequence) – 단순히 다음 명령문으로 감
2. 선택(Selection) – 최소한 다음 두 가지 중 하나의 선택
– 바로 다음 명령문으로 가거나
– 혹은 다른 명령문으로 점프
3. 반복(Repetition) - 루프 (코드 블록의 반복)
루프(loop)의 끝에서
– 앞으로 되돌아 가서 코드 블록을 반복하거나
– 혹은 블록 다음의 명령문에서 계속
선택(Selection)과 반복(Repetition)은 제어 흐름에서 분기 지점(branch
points)을 나타내므로 분기(Branching)라고 부른다.
문제해결을 위한 C언어 프로그래밍
2
C 언어의 제어 흐름을 나타내는 문
순차(Sequence)


분기: 선택(Selection)
디폴트(the default)
분기문(branching statement
)을 사용하지 않는 이상 C는
자동적으로 다음 명령문을
실행한다.




if
if-else
if-else if-else if- … - else
switch
분기: 반복(Repetition)



Chapter 4
while
do-while
for
문제해결을 위한 C언어 프로그래밍
3
단순 선택 프로그램

예제 4.1
»
»
»
»
»
Chapter 4
문제: 만약 $10,000 이상의 소득이라면 소득세를 부과하고, 아니면 면세
알고리즘:
– if gross_income is greater than $10,000
compute city_tax = 0.0175 × gross_income
else
set city_tax to 0
end_if
프로그램: 그림 4.2
– if (gross_income > 10000.00)
city-tax = CITY_TAX_RATE * gross_income;
else
city_tax = 0.0;
순서도: 그림 4.3
관계 연산자: ==, !=, <, <=, >, >=
문제해결을 위한 C언어 프로그래밍
4
Chapter 4
문제해결을 위한 C언어 프로그래밍
5
If 문의 순서도
Chapter 4
문제해결을 위한 C언어 프로그래밍
6
C 언어의 관계 연산자
Math
Notation Name
=
equal to
Chapter 4

not equal to
>
greater than
C
C
Notation Examples
==
balance == 0
answer == 'y'
!=
income != tax
answer != 'y'
>
income > outgo

greater than or equal to
>=
points >= 60
<
less than
<
pressure < max

less than or equal to
<=
income <=
outgo
문제해결을 위한 C언어 프로그래밍
7
관계 연산자의 사용 예
예제 4.2
예제 4.3
Chapter 4
문제해결을 위한 C언어 프로그래밍
8
산술 연산자와 관계 연산자의 우선 순위





Chapter 4
C 언어의 식(expressions)은 실제 산술식의 규칙과 유사
괄호 안의 우선 순위(precedence)가 가장 높음
우선 순위가 정확하고 분명할 때에는 괄호를 써서 식을 난잡하게 만들 필요
없음
예제 4.4: if (b * b – 4 * a * c >= 0)
C 연산자의 우선 순위: (), + -(단항), * / , + -(이항), < <= > >=, == != , =
문제해결을 위한 C언어 프로그래밍
9
산술 연산자와 관계 연산자의 우선 순위(계속)

Chapter 4
예제 4.5: a + b >= 3 * c == a != 2 * c + b
(a, b, c가 각각 10, 3, 7이라고 가정)
문제해결을 위한 C언어 프로그래밍
10
산술 연산자와 관계 연산자의 우선 순위(계속)

Chapter 4
예제 4.6: (a + b >= 3 * c) == (a != 2 * c + b)
(a, b, c가 각각 10, 3, 7이라고 가정)
문제해결을 위한 C언어 프로그래밍
11
C 언어의 If 문




Chapter 4
단순 선택(Simple selection)
조건식의 계산 결과가 참(0 이외의 값)이라면 조건식 다음의
문장을 실행하고, 거짓(0)이라면 건너 뜀
문법:
if (조건식)
Action if true;//execute only if true
next action;//always executed
가독성(readability)을 위해 indentation (컴파일이나 실행의
정확성과 무관)
문제해결을 위한 C언어 프로그래밍
12
if 문의 예
if(eggsPerBasket < 12)
//begin body of the if statement
printf(“Less than a dozen eggs per basket\n”);
//end body of the if statement
totalEggs = numberOfEggs * eggsPerBasket;
printf(“You have a total of %d eggs.\n“ totalEggs);


Chapter 4
if 문의 몸체(body)는 조건에 따라 실행
if 문의 몸체 다음의 문장들은 항상 실행
문제해결을 위한 C언어 프로그래밍
13
if 문의 조건식(산술식, 문자열)




Chapter 4
예제 4.7
» if (number – number / 2 * 2)
printf(“Odd”);
else
printf(“Even”);
예제 4.8
» if (number – number / 2 * 2)
printf(“odd”);
예제 4.9
» if (number – number / 2 * 2)
;
else
printf(“Even”);
예제 4.10
» if (3 * x – 15) {
printf(“Your integer is not the solution of 3x – 15 = 0.\n”);}
else
printf(“Your integer is the solution of 3x – 15 = 0.”);
문제해결을 위한 C언어 프로그래밍
14
if 문의 조건식(산술식, 문자열)

예제 4.11
» Char string1[21], string2[21]
strcpy(string1, string2)
printf(“String1 contains: %s”, string1);
printf(“String2 contains: %s”, string2);

Chapter 4
예제 4.12
» if (strcmp(string1, string2) > 0)
printf(“%s is greater than %s”, string1, string2);
else
printf(“%s is not greater than %s”, string1, string2);
문제해결을 위한 C언어 프로그래밍
15
C 언어의 블록:
복합문(compound statements)


Action if true 부분이 하나의 문장이거나 중괄호(curly
brackets)로 둘러 싸인 복합문(compound statement, or block)일
수도 있음
보기:
if(eggsPerBasket < 12)
{ //begin body of the if statement
printf(“Less than a dozen per basket\n”);
costPerBasket = 1.1 * costPerBasket;//charge 10% more
}
//end body of the if statement
totalEggs = numberOfEggs * eggsPerBasket;
printf(“You have a total of %s eggs.\n“, totalEggs);
Chapter 4
문제해결을 위한 C언어 프로그래밍
16
Two-way 선택 : if-else



두 개의 옵션(options) 중에서 하나를 선택
조건식의 결과값에 따라 Action1 혹은 Action2 중의 하나가 실행
문법:
if (조건식)
{
Action1 //execute only if true
}
else
{
Action2//execute only if false
}
Action3//always executed
Chapter 4
문제해결을 위한 C언어 프로그래밍
17
if-else 보기

단일 문장을 가진 예:
if(time < limit)
printf(“You made it.\n”);
else
printfln(“You missed the deadline.\n”);

복합문을 가진 예:
if(time < limit)
{
printf(“You made it.\n”);
bonus = 100;
}
else
{
printf(“You missed the deadline.\n”);
bonus = 0;
}
Chapter 4
문제해결을 위한 C언어 프로그래밍
18
다중 선택:
if-else if-else if-…-else


두 가지 이상의 가능성을 가진 상황을 처리하는 방법
문법:
if(조건식_1)
Action_1
else if(조건식_2)
Action_2
.
.
.
else if(조건식_n)
Action_n
else
Default_Action
Chapter 4
문제해결을 위한 C언어 프로그래밍
19
if-else if-else if-…-else 보기
if(score >= 90)
grade = ‘A’;
else if (score >= 80)
grade = ‘B’;
else if (score >= 70)
grade = ‘C’;
else if (score >= 60)
grade = ‘D’;
else
grade = ‘E’;
Chapter 4
문제해결을 위한 C언어 프로그래밍
20
결합 if 문과 다중선택
예제 4.13: 비결합 if 문(그림 4.6) => 결합 if 문(그림 4.8)
if(filing_status ==1)
printf(“Single”);
else if (filing_status == 2)
printf(“Married filing jointly”);
else if (filing_status == 3)
printf(“Married filing seperately”);
else if (filing_status == 4)
printf(“Head of household”);
else
printf(“Error in filing status”);
Chapter 4
문제해결을 위한 C언어 프로그래밍
21
(참고) 다중 선택(9장):
switch




다중 선택을 구현하는 또 다른 방법
Controlling_Expression 부분은 반드시 char, int, short
Controlling Expression 과 Case_Label 부분은 반드시 동일한
데이터형
break 는 생략 가능
switch(Controlling_Expression)
{
case Case_Label:
statements
…
break;
case Case_Label:
statements
…
break;
<위의 cases의 수는 임의의 개수 가능>
<다음의 default case는 생략 가능>
default:
statements
…
break;
}
Chapter 4
문제해결을 위한 C언어 프로그래밍
22
switch 보기
switch(seatLocationCode)
{
case 1:
printf(“Orchestra\n”);
price = 40.00;
break;
case 2:
printf(“Mezzanine\n”);
price = 30.00;
break;
case 3:
printf(“Balcony\n”);
price = 15.00;
break;
default:
printf(“Unknown seat code\n”);
break;
}
Chapter 4
문제해결을 위한 C언어 프로그래밍
23
제어된 반복을 위한 프로그래밍




예제 4.15: 프로그램을 한 번 실행하여 세금 계산을 반복
그림 4.2 => 그림 4.12
» while the user wants to continue
수정된 알고리즘: 그림 4.13
» set want_to_continue to ‘y’
while want_to_continue is equal to ‘y’
…
print “Do you want to continue? (y/n):”
read want_to_continue
프로그램: 그림 4.14
» char want_to_continue = ‘y’;
while (want_to_continue == ‘y’) {
…
printf(“Do you want to continue? Type y/n: ”);
scanf(“%c”, &want_to_continue);
}
Chapter 4
문제해결을 위한 C언어 프로그래밍
24
반복(Repetition): 루프(Loop)


정해진 반복 횟수 혹은 정해진 조건 하에서 코드 블록을 반복
기본 구조:
» 대개 초기화(initialization)부분을 가짐
» 루프의 몸체(body)
» 루프 종결(termination)검사 부분

논리적인 구성
»
»
»
»

반복 횟수 지정
Sentinel 제어 루프
무한 루프(infinite loops)
반복이 없거나 한 번의 반복
반복 명령문의 종류
» While (선 검사 반복문: 그림 4.15)
» do-while (후 검사 반복문: 그림 4.16)
» For (선 검사 반복문: 그림 4.15)
Chapter 4
문제해결을 위한 C언어 프로그래밍
25
while 루프

문법:
while(Expression)
{
//body of loop
First_Statement;
...
Last_Statement;
}




Chapter 4
초기화를 담당하는 문장이 항상 루프의 앞에 위치
Expression 은 루프 종료 검사 부분에 해당
루프의 몸체(body)에서 Expression 을 false로 만드는 부분이
있어야 무한 루프 방지
반복 횟수가 지정된 루프 혹은 sentinel 루프 가능
» sentinel 루프가 바람직한 선택
문제해결을 위한 C언어 프로그래밍
26
while : 반복 횟수 지정 루프의 예

Chapter 4
사용자가 10개의 데이터를 입력
int next;
//Loop initialization
int count = 1;
int total =0;
while(count <= 10) //Loop termination condition
{ //Body of loop
scanf(“%d”, &next);
total = total + next;
count++; //Loop termination counter
}
문제해결을 위한 C언어 프로그래밍
27
while:
sentinel 제어 루프의 예


Chapter 4
사용자가 양수인 데이터를 입력
next 변수가 sentinel 역할을 함

루프는 사용자가 음수를 입력할 때 종결됨
//Initialization
int next = 0;
int total = 0;
while(next >= 0)//Termination condition
{ //Body
total = total + next;
scanf(“%d”, &next);
}

예제 4.17: 입력된 정수의 제곱을 구하는 프로그램, 0이 입력되면 종료
문제해결을 위한 C언어 프로그래밍
28
while: 반복 횟수가 0인 루프

처음 입력된 값이 루프의 조건식을 만족하지 못하므로 while
루프의 몸체가 전혀 실행되지 않음
//Initialization
int next;
int total = 0;
scanf(“%d”, &next);
while(next >= 0)//Termination condition
{ //Body
total = total + next;
scanf(“%d”, &next);
}

Chapter 4
사용자가 처음에 입력한 데이터가 음수라면, 루프의 몸체는
결코 실행되지 않음
문제해결을 위한 C언어 프로그래밍
29
팩토리얼(factorial)구하기

예제 4.16
» 주어진 양수(n)의 팩토리얼(n!: fact(n) = 1 × 2 × … × n)
구하기
» 정의
fact(1) = 1, fact(2) = 1 × 2 = fact(1) × 2, … fact(n) = fact(n-1) × n
» 프로그램
fact = 1;
count = 2;
while (count <= n) {
fact = fact * count;
count = count + 1;
} /* end while */
Chapter 4
문제해결을 위한 C언어 프로그래밍
30
do-while 루프 (9장)

문법
do
{ //body of loop
First_Statement;
...
Last_Statement;
} while(Expression);




Chapter 4
초기화 부분이 루프 몸체 앞 부분에 위치할 수 있음
루프 몸체 다음에 조건식이 위치하므로 최소한 한 번은 반드시 실행
(최소한 한 번의 반복)
반복 횟수 지정 루프 혹은 sentinel 루프 가능
» sentinel 루프가 바람직한 선택
루프의 몸체에서 Expression 을 false 로 만드는 부분이 있어야
무한 루프 방지
문제해결을 위한 C언어 프로그래밍
31
do-while 루프의 예
int count = 1;
int number = 10;
do //Display integers 1 - 10 on one line
{
printf(“%d,”, count);
count++;
}while(count <= number);
Note: printf(“%d\n,”, count); 이 아니라 printf(“%d,”,
count); 이 사용되었으므로 숫자들이 한 라인에 출력
Chapter 4
문제해결을 위한 C언어 프로그래밍
32
for 루프(9장)



반복 횟수 지정 루프의 가장 바람직한 선택
초기화 부분, 루프 검사 조건식, 루프 카운터 변경 부분이 함께
구성됨
문법:
for(Initialization; Expression; After_Loop_Body)
loop body;

Chapter 4
실행 순서:
1. Initialization – 루프의 첫 번째 반복에서만 실행
2. Expression – 루프 검사 조건식
3. loop body - 루프 검사 조건식이 true 일 때에만 실행
4. After_Loop_Body – 일반적으로 루프 카운터를 변경하는 부분
5. Expression – 루프 검사를 반복 (2 단계 반복), 등.
문제해결을 위한 C언어 프로그래밍
33
for 루프의 예

9 부터 0 까지의 카운트 다운
for(int count = 9; count >= 0; count--)
{
printf("T = %d“, count);
printfln(" and counting\n");
}
printfln("Blast off!\n");
Chapter 4
문제해결을 위한 C언어 프로그래밍
34
구조적 프로그래밍
Chapter 4

가능하면 goto 문을 쓰지 않고, 세 가지 기본적인 제어
구조(순차, 선택, 반복)를 이용함으로써 쉽고 논리적인
프로그램을 만드는 규칙

Java를 비롯한 최신의 언어에서는 goto 문을 쓸 수 없음
문제해결을 위한 C언어 프로그래밍
35