본문 바로가기
C++

[C++] C++ 제어문 - 조건문

by codingbird1234 2024. 9. 24.

제어문은 프로그램의 흐름을 제어하는 중요한 요소입니다.

제어문에는 크게 조건문반복문이 있습니다.

오늘은 조건문에 대해 알아보겠습니다.

 

  • 조건문은 특정 조건을 만족할 때만 코드를 실행하거나, 조건에 따라 다른 코드를 실행하도록 하는 기능을 합니다.
  • 크게 if, if-else, else if, switch
번호 조건문 종류 설명
1 if if는 조건이 참일 때 코드 블록을 실행하는 구조
2 if-else 조건이 참일 때와 거짓일 때 서로 다른 코드를 실행
3 else if 여러 조건을 연속해서 검사 / 조건이 맞는 첫 번째 블록만 실행
4 switch 값에 따라 여러 경우 중 하나를 선택하여 실행

 

1. if 문

#include <iostream>

int main() {
    int x = 10;
    if (x > 5) {
        std::cout << "x is greater than 5" << std::endl;
    }
    return 0;
}
  • if의 괄호 안에 있는 식이 조건식입니다.
  • 조건식이 참인 경우에만 if의 중괄호 안에 있는 코드가 실행됩니다.

2. if-else 문

#include <iostream>

int main() {
    int x = 3;
    if (x > 5) {
        std::cout << "x is greater than 5" << std::endl;
    } else {
        std::cout << "x is not greater than 5" << std::endl;
    }
    return 0;
}
  • if의 조건식이 참인 경우에는 if의 중괄호 안에 있는 코드만 실행됩니다.
  • 조건식이 거짓인 경우에는 else의 중괄호 안에 있는 코드만 실행됩니다.

3. else if 문

#include <iostream>

int main() {
    int x = 7;
    if (x > 10) {
        std::cout << "x is greater than 10" << std::endl;
    } else if (x > 5) {
        std::cout << "x is greater than 5 but less than or equal to 10" << std::endl;
    } else {
        std::cout << "x is less than or equal to 5" << std::endl;
    }
    return 0;
}
  • else if는 else와 다르게, 조건식을 설정할 수 있습니다.
  • 차례대로 조건식을 확인하고, 처음으로 조건식이 참인 경우에만 이에 해당되는 코드를 실행합니다.
  • 만약 끝까지 조건식이 거짓인 경우에는 else의 코드가 실행됩니다.(else를 꼭 설정해야 하는 것은 아닙니다.)

4. switch 문

#include <iostream>

int main() {
    int day = 3;

    switch (day) {
        case 1:
            std::cout << "Monday" << std::endl;
            break;
        case 2:
            std::cout << "Tuesday" << std::endl;
            break;
        case 3:
            std::cout << "Wednesday" << std::endl;
            break;
        case 4:
            std::cout << "Thursday" << std::endl;
            break;
        case 5:
            std::cout << "Friday" << std::endl;
            break;
        default:
            std::cout << "Weekend" << std::endl;
    }
    return 0;
}
  • break는 조건에 맞는 블록을 실행한 후 switch문을 빠져나가게 합니다.
  • break가 없는 경우, 조건에 맞는 case를 만나면 그 이후의 모든 case가 연속적으로 실행됩니다.
  • default는 어떠한 경우에도 맞지 않을 때 실행됩니다.

'C++' 카테고리의 다른 글

[C++] C++ 함수  (0) 2024.09.25
[C++] C++ 제어문 - 반복문  (0) 2024.09.25
[C++] C++ 기본 자료형(+문자열)  (0) 2024.09.24
[C++] C++ 입출력  (0) 2024.09.24