C 반복 while - sonkoni/Koni-Wiki GitHub Wiki

반복문 while 은 조건식이 참일 경우 루프를 반복하고, 거짓이면 블록을 빠져나간다.

초기식
while (조건식) {
  참일 때 반복코드
  변화식
}
#include <stdio.h>
int main(int argc, char *argv[]) {
    int i = 0;
    while (i < 10) {
        printf("%d. Hello\n", i);
        i++;
    }
    return 0;
}
#include <stdio.h>
int main(int argc, char *argv[]) {
    while (10 > i++) {
        printf("%d. Hello\n", i - 1);
    }
    return 0;
}

세미콜론 주의

while (i < 10); { /*** WRONG 세미콜론을 붙이면 안 블럭이 루프로 평가되지 않는다. ***/
  ...
}

입력 횟수만큼 출력

#include <stdio.h>
int main(int argc, char *argv[]) {
    int count;
    printf("반복할 횟수:");
    scanf("%d", &count);
    int i = 0;
    while (i < count) {
        printf("%d. Hello\n", i + 1);
        i++;
    }
    return 0;
}

while 은 반복 횟수가 정해지지 않은 경우 유용

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char *argv[]) {
    srand(time(NULL));
    int i = 0;
    while (i != 3) {
        i = rand() % 10;
        printf("-> %d\n", i);
    }
    return 0;
}
// -> 4
// -> 6
// -> 3

while 로 무한루프 만들기

무한루프는 for(;;) {} 로도 만든다.

// 숫자 0을 넣을 때까지 무한반복
#include <stdio.h>
int main(int argc, char *argv[]) {
    while (1) { // stdbool.h 를 받았다면 true 로 해도 됨
        int i;
        printf("=> ");
        scanf("%d", &i);
        if (!i) {
            printf("Good-Bye!");
            return 0;
        }
    }
    return 0;
}
⚠️ **GitHub.com Fallback** ⚠️