C
반복문(while, do ~ while, for), if 문
김꼬알
2023. 3. 14. 19:09
반복문 종류
for
- 정해진 횟수만큼 반복
while
- 조건이 만족하는 동안 반복
do ~ while
- 무조건 한번 수행 후 조건이 만족하는 동안 반복
while 구조
while( 조건 )
{
수행하는 작업들
}
int i = 0;
while(i < 3) // i 값이 3보다 작다는 조건을 만족할 때까지 아래 연산 수행
{
printf("i = : %d\n", i);
i++;
}
printf("sum = : %d\n", i); // sum = : 3값이 출력됨
#include<stdio.h>
int main(){
int count = 2;
int sum = 0;
while(count <= 10){
sum += count; // sum = sum + count
count += 2; // count = count + 2
}
print("%d", sum); // count = 12, sum = 30 이므로 30이 출력됨
}
do ~ while 구조
do
{
수행하는 작업들
} while ( 조건 )
int i = 3;
do
{
printf("i = %d\n", i); // i = 3
i++; // 3 + 1 이므로 4
} while( i < 3); // 4 < 3 은 거짓이므로 더이상 수행하지 않고 아래로 내려감
printf("sum = %d\n", i); 4가 출력됨
#include <stdio.h>
void main(){
int a, b;
a = 2;
while( a-- > 0){ // 조건이 만족하지 않을 때까지 수행한 다음 for문 수행
printf("a = %d\n", a);
}
for( b = 0; b < 2; b++ ){ // b < 2가 만족하면 {조건} 수행 후 b++ 해줌
printf("a = %d\n", a++);
}
}
#include <stdio.h>
int main(){
int a=120, b=45;
while( a != b){ // (조건)이 만족하면 if문 수행
if ( a>b ) a = a - b; // a>b 가 참이면 if문 수행, 거짓이면 else 수행
else b = b - a;
}
printf("%d", a); // while의 조건이 거짓이면 최종적으로 수행
}