[C] 3강. 반복문

반복문


반복문의 개념

반복문의 조건


반복의 종료 시점


반복의 횟수 조절


반복문의 구조


반복문의 종류

while 문


int cnt;
cnt = 0;

while(cnt < 5) {
    printf("hello\n");
    cnt++;
}


do-while 문


int cnt;
cnt = 0;

do {
    printf('hello world');
    cnt++;
} while(cnt < 10);


while do-while
조건을 검사하고 문장을 실행 문장을 실행하고 조건을 검사
0회 반복이 가능 최소 1회 반복


hello를 5회 출력하는 program (적어도 한 번은 출력)

int cnt;
cnt = 0;

do {
    printf('hello\n');
    cnt = cnt + 1;
} while (cnt < 5);


for 문


int cnt;

for (cnt = 0; cnt < 5; cnt = cnt + 1) {
    printf('hello\n');
}


두 수를 입력 받아 합을 출력하는 것을 5회 반복하는 program 작성

int a, b, cnt;

for (cnt = 0; cnt < 5; cnt = cnt + 1) {
    printf("Enter 1st number: ");
    scanf("%d", &a);
    // scanf를 쓰게되면 표준 입력을 받아서 a 변수에 저장
    printf("Enter 2nd number: ");
    scanf("%d", &b);
    // scanf를 쓰게되면 표준 입력을 받아서 b 변수에 저장
    printf("SUM = %d\n", a+b);
    // 더한 값 출력
}


반복문의 활용

1에서 10까지의 수를 화면에 출력

int i;

for (i=0; i<10; i++) {
    printf("%d\n", i+1);
}

// 1
// 2
// 3
// 4
// 5
// 6
// 7
// 8
// 9
// 10


C언어 문법 익혀두기 (개념은 프로그래밍이 거기서 거기…)


반복 횟수를 입력 받고, 그 횟수만큼 정수를 입력 받아 평균을 출력하기

#include<stdio.h>

void main() {
    int i, num, cnt, sum;

    printf("몇 회를 반복할 것인가요?");
    scanf("%d", &cnt);
    printf("%d회 반복하여 정수를 입력하세요\n", cnt);

    for (i = 0; i < cnt; i++) {
        scanf("%d", &num);
        sum = sum + num;
    }
    printf("평균은 %d", sum/cnt);
}