소프트웨어/C
[2004년 기말 9번] 반복 계산 - 제어/반복
카켈
2007. 2. 12. 00:41
1. 목적
- 다양한 반복/제어문에 대한 이해를 한다.
2. 문제 (점수 : 10 점)
- 세가지 반복문(for/while/do-while) 을 써서 1부터 100까지 합을 계산하는 프로그램을 작성한다.
- 출력 화면
1부터 100까지의 누적합 계산
for 문만을 이용한 결과 : 5050
while 문만을 이용한 결과 : 5050
do-while 문만을 이용한 결과 : 5050
Press any key to continue
for 문만을 이용한 결과 : 5050
while 문만을 이용한 결과 : 5050
do-while 문만을 이용한 결과 : 5050
Press any key to continue
3. 이해
- 다양한 반복문을 이해하는가?
4. 코드
#include <stdio.h>
int main()
{
int i, total;
i = total = 0;
puts("1부터 100까지의 누적합 계산");
for(i = 1; i <= 100; i++) total += i;
printf("for 문만을 이용한 결과 : %d", total);
putchar('\n');
total = 0;
i = 1;
while(i <= 100)
{
total += i;
i++;
}
printf("while 문만을 이용한 결과 : %d", total);
putchar('\n');
total = 0;
i = 1;
do
{
total += i;
i++;
}while(i <= 100);
printf("do-while 문만을 이용한 결과 : %d", total);
putchar('\n');
return 0;
}
5. 해설
- 각각 선언하는 형식은 다르지만 작동 방식(메카니즘)은 동일합니다.
6. 참고
- http://www.winapi.co.kr/clec/cpp1/4-3-2.htm : for/while/do-while 제어문 비교
- 유사 문제