횟수가 정해진 반복
화면에 "hello world\n"을 다섯 줄 출력=>printf 함수 다섯 번 호출
단순이 이렇게 적을 수 있지만 500번 호출하려면 500번을 그대로 다 써야하는가? 아니다.
반복문을 사용한다면 훨씬 편리할 것이다. 흐름도를 살펴보자.
#include <stdio.h>
int main()
{
int count=0;
while(count<500){
printf("hello world\n");
count++;
}
return 0;
}
그러나 위처럼 단순한 반복은 없다.
예) 1부터 1000까지 합 구하기.
#include <stdio.h>
int main()
{
int count=1;
int sum=0;
while(count<=1000){
sum+=count;
count++;
}
printf("1-1000까지의 합은 : %d\n",sum);
return 0;
}
while 문 내부 계산 내용 및 결과는 얼마든지 복잡할 수 있다.
예2) 짝수 홀수 별 총합 구하기.
#include <stdio.h>
int main()
{
int start,end,temp;
int sum=0;
int even_sum=0;
int odd_sum=0;
scanf("%d %d",&start,&end);
if(start>end){
temp=end;
end=start;
start=temp;
}
while(start<=end){
if((start%2)==0){
even_sum+=start;
}
else if((start%2)==1){
odd_sum+=start;
}
start++;
}
printf("even_sum=%d\n",even_sum);
printf("odd_sum=%d\n",odd_sum);
return 0;
}
'Computer engineering > C' 카테고리의 다른 글
반복문-for (0) | 2021.05.06 |
---|---|
반복문-While(2) (0) | 2021.05.02 |
반복문-While(1) (0) | 2021.05.02 |
If-else 조건문 (0) | 2021.04.21 |
If 조건문 (0) | 2021.04.11 |