C언어

조건과 분기

khon98 2020. 12. 16. 15:44

1. if, else

#include <stdio.h>

int main(void) {
    // 버스를 탄다고 가정. 학생과 일반인으로 구분(일반인은 20세)
    int age = 25;
    if (age >= 20) { // 조건, age가 20보다 크거나 같으면
        printf("일반인 입니다. \n");
    }
    else { // 그게 아니라면
        printf("학생입니다. \n");
    }
}

 

2. else if

- else if 구문은 계속 나올 수 있음, 조건에 맞도록 여러 번 선언할 수 있음

#include <stdio.h>

int main(void) {
    // 초등학생(8 ~ 13) 중학생(14 ~ 16) 고등학생(17 ~ 19)
    int age = 30;
    if (age >= 8 && age <=13) { // age 값이 8보다 크거나 같고 13보다 작거나 같으면(&&)
        printf("초등학생 입니다.\n");
    }
    else if (age >= 14 && age <= 16) { // age 값이 14보다 크거나 같고 16보다 작거나 같으면(&&)
        printf("중학생 입니다.\n");
    }
    else if (age >= 17 && age <= 19) { // age 값이 17보다 크거나 같고 19보다 작거나 같으면(&&)
        printf("고등학생 입니다.\n");
    }
    else { // 모든 조건에 만족하지 않는 경우 실행
        printf("학생이 아닙니다.\n");
    }
}

 

3. break, continue

break

#include <stdio.h>

int main(void) {
    // 1번부터 30번까지 있는 반에서 1번에서 5번까지 조별 발표를 합니다
    for (int i = 1; i <= 30; i++) {
        if (i >= 6) {
            printf("나머지 학생은 귀가.\n");
            break; // for문을 탈출
        }
        printf("%d번 학생이 조별 발표 준비.\n", i);
    }
}

 

continue

#include <stdio.h>

int main(void) {
    // 1번 부터 30번 까지 있는 반에서 7번은 결석
    // 7번을 제외한 6번부터 10번까지 조별 발표 준비
    for (int i = 1; i <= 30; i++) {
        if (i >= 6 && i <= 10) {
            if (i == 7) {
                printf("%d번 결석.\n", i);
                continue; // 조건에 맞으면 다음 코드는 넘어감
            }
            printf("%d번 학생은 발표 준비.\n", i);
        }
    }
}

 

4. &&(and), ||(or)

- &&(and) : 둘 다 맞아야 다음 코드 실행

#include <stdio.h>

int main(void) {
    // && ||
    int a = 10;
    int b = 10;
    int c = 13;
    int d = 13;
    if (a == b && c == d) {
        printf("a와 b가 같고, c와 d도 같음.\n");
    }
    else {
        printf("값이 다름.\n");
    }
}

 

- ||(or) : 앞에 조건과 뒤에 조건 둘 중에 하나라도 맞으면 코드 실행 

#include <stdio.h>

int main(void) {
    // && ||
    int a = 10;
    int b = 11;
    int c = 13;
    int d = 13;
    if (a == b || c == d) { // a와 b가 같거나 혹은 c와 d가 같으면 다음 코드 실행
        printf("a와 b 혹은 c와 d의 값이 같음.\n");
    }
    else {
        printf("값이 다름.\n");
    }
}

 

5. 랜덤

rand(): 랜덤 수를 뽑을 수 있음

#include <time.h>
#include <stdlib.h>
#include <stdio.h>

int main(void) {
    printf("난수 초기화 이전.\n");
    for (int i = 0; i < 10; i++) {
        printf("%d", rand() % 10); // 0 ~ 9 중에 랜덤으로 숫자를 뽑음
    }
    srand(time(NULL)); // 난수 초기화
    printf("\n\n난수 초기화 이후.\n");
    for (int i = 0; i < 10; i++) {
        printf("%d", rand() % 10); // 0 ~ 9 중에 랜덤으로 숫자를 뽑음
    }
    return 0;
}

 

* 가위 바위 보

#include <time.h>
#include <stdlib.h>
#include <stdio.h>

int main(void) {
    // 가위 0, 바위 1, 보 2
    srand(time(NULL));
    int i = rand() % 5; // 0 ~ 5 반환
    if(i == 0) { // i가 0일 경우
        printf("가위\n");
    }
    else if (i == 1) {
        printf("바위\n");
    }
    else if (i == 2) {
        printf("보\n");
    }
    else {
        printf("모름\n");
    }
    return 0;
}

 

6. switch case

switch - 값을 받아서 값이 해당하는 경우에 맞도록 출력

case - 문장이 끝날 때는 break를 입력해야 함

#include <time.h>
#include <stdlib.h>
#include <stdio.h>

int main(void) {
    // 가위 0, 바위 1, 보 2
    srand(time(NULL));
    int i = rand() % 5; // 0 ~ 5 반환
    switch (i) {
        case 0:printf("가위\n"); break;
        case 1:printf("바위\n"); break;
        case 2:printf("보\n"); break;
        default:printf("모름\n"); break;
    }
    return 0;
}

 

7. 프로젝트

#include <time.h>
#include <stdlib.h>
#include <stdio.h>

int main(void) {
    srand(time(NULL));
    int num = rand() % 100 + 1; // 1 ~ 100 반환
    printf("숫자 : %d\n", num);
    int answer = 0; // 정답
    int chance = 5; // 기회
    while (1) { // 기회 카운트, 1 : 참, 0 : 거짓
        printf("남은 기회 %d번\n", chance--);
        printf("숫자를 맞혀보세요 (1~100) : ");
        scanf("%d", &answer);
        
    if (answer > num) { // 입력한 숫자가 정답보다 큰 경우
        printf("DOWN\n\n");
    }
    else if (answer < num) { // 입력한 숫자가 정답보다 작은 경우
        printf("UP\n\n");
    }
    else if (answer == num) {
        printf("정답\n\n");
        break;
    }
    else { // 모든 경우가 아닌 경우
        printf("알 수 없는 오류 발생.\n\n");
    }
    if (chance == 0) {
        printf("모든 기회 소진\n\n");
        break;
        }
    }
    return 0;
}