..열심히 공부하세../C 입문

[08] while문, do~while문

댄스댄스 2012. 5. 25. 17:57

* 반복문

for(초기값; 종료값 또는 조건식; 증감)
{

}


while(조건문)
{
    처리내용;
}

 

int n=5;
while(n<10)
{
   printf("happy");
   n=n+1;

}


do{

  처리내용

} while(조건문);


int n=5;

do{
  printf("happy");
} while(n<10);


* while문 do~while문은 조건이 맞으면 결과값은 동일하다.

  조건이 틀리면 결과값이 다르다(주의)

* do~while문은 조건과 무관하게 무조건 1회는 실행된다.


// 조건이 맞았을 경우

int p=5, q=5;

while(p<10)
{
   printf("happy");
   p++;
}

printf("p=%d\n",p);


do{
  printf("happy");
  q++;
} while(q<10);

printf("q=%d\n",q);


// 조건이 맞이 않았을 경우

int p=50, q=50;

while(p<10)
{
   printf("happy");
   p++;
}

printf("p=%d\n",p);


do{
  printf("happy");
  q++;
} while(q<10);

printf("q=%d\n",q);

----------------------------

- for반복문은 반복횟수를 정확히 파악하는 경우에 주로 사용된다
- while문은 반복횟수를 정확히 알지 못할때 주로 사용될 수 있다.
   예) 마지막 데이터를 만날때까지 반복해라
        EOF (End Of File)
        BOF (Begin Of File)
- do~while 메인카테고리 접근시 주로 사용된다.

----------------------------------

* break문
  switch~case문을 빠져나올때
  반복문을 빠져나올때


int n;
for(n=1; n<10; n++)
{
   printf("happy");
   if(n==5) break;
}

* continue문
  반복문으로 다시 가서 수행

int n;
for(n=1; n<10; n++)
{
   if(n==5) continue;
   printf("happy");
}

-------------------------------------------

 

#include <stdio.h>
void main()
{

/*
int n=5;
while(n<10)
{
   printf("happy");
   n=n+1;

}
*/

/*
int n=5;

do{
  printf("happy");
  n=n+1;
} while(n<10);

*/
/*
int p=5, q=5;

while(p<10)
{
   printf("happy");
   p++;
}

printf("p=%d\n",p);


do{
  printf("happy");
  q++;
} while(q<10);

printf("q=%d\n",q);


*/

/*
int p=50, q=50;

while(p<10)
{
   printf("happy");
   p++;
}

printf("p=%d\n",p);


do{
  printf("happy");
  q++;
} while(q<10);

printf("q=%d\n",q);

*/
/*
int n;
for(n=1; n<10; n++)
{
   printf("happy");
   if(n==5) break;
}
*/

 

}