[C/C++/VC++] while문
형식
while(조건식)
실행문장; | | *조건식에 만족하는 동안 { } 안의 문장을 반복 수행하고 만족하지 않으면 while 다음 문장을 수행 *while(1) 문 : 무한대 반복 수행 *while(0) 문 : 한번도 수행하지 않음
예제 4) /* while 문 사용실습 : Ctrl+Z 입력시 까지 정수 입력받아 합, 평균 구하기 */ #include<stdio.h> main() { int x, n=0, sum=0; clrscr(); while(scanf("%d", &x) != EOF) { sum += x; n = n + 1; } printf("합 = %d\n", sum); printf("평균 = %d\n", sum/n); getch(); }
#. EOF *-1 값을 갖는 기호상수로 scanf 문 등에서 Ctrl+Z 을 입력받을시 데이터의 끝임을 알림 *stdio.h 파일 include 해야함 | * while 문내에 조건식이 항상 참이면 무한루프로 빠져 while 문을 벗어나지 못한다.
예제 5) #include<stdio.h> main(){
char name[20],ch;
int age;
clrscr();
while(1) /*조건이 항상 참이므로 무한루프에 빠진다. */
{
printf("input name :");
gets(name);
printf("input age : ");
scanf("%d",&age);
printf("NAME : %s AGE : %d\n", name,age);
printf(" continue? 종료 : N\n");
fflush(stdin);
ch=getch();
if (ch=='n' || ch == 'N') /*입력받은 값이 'N' 이면 while 문을 빠져 나가는 조건 */
break;
} } 예제 5 실행결과 보기
예제 6) #include<stdio.h> main(){
int a,b;
a=b=0;
while(a<5)
{
++a;
while(b<a)
{
putchar('*');
++b;
}
putchar('\n');
b=0;
} } |
do ~ while 문
형식
*{ } 안의 문장을 무조건 한번 수행 후, 조건식이 만족하는 동안 { } 안의 문장을 반복 수행한다.
예제 7) #include<stdio.h> #include<conio.h> main(){ int a,b; char op; printf(" Enter two numbers : "); scanf("%d %d",&a,&b); printf(" Add,Subtract,Multiply,or Divide ? \n"); do { printf("enter the first letter :"); op=getch(); printf("\n"); }while(op!='A' && op !='S' && op!='M' && op!='D'); if(op=='A') printf("%d\n",a+b); else if(op=='S') printf("%d\n",a-b); else if(op=='M') printf("%d\n",a*b); else if(op=='D' ) printf("%d\n",a/b); } |
출처 : http://www.it-bank.or.kr/prom/c_main.htm