산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> C 언어

C++ 조건문 마스터하기: if, if-else, 중첩 if-else 완벽 해설

C++ if, if-else, 중첩 if-else

예제를 통해 의사결정 프로그램을 만드는 if-else 문의 사용법을 배워보세요.

컴퓨터 프로그래밍에서 if...else 문은 특정 조건 하에서 한 코드 블록을, 다른 조건 하에서 다른 코드 블록을 실행하기 위해 사용합니다.

예: 학생의 점수에 따라 등급(A, B, C) 부여


C++에는 세 가지 형태의 if...else 문이 있습니다.

  1. if 문
  2. if...else 문
  3. if...else if...else 문

C++ if 문

if 문의 문법:

if (condition) {
    // if 문 본문
}

if 문은 괄호 ( ) 안의 condition을 평가합니다.

참고: { } 안의 코드가 if 문의 본문입니다.

C++ 조건문 마스터하기: if, if-else, 중첩 if-else 완벽 해설

예제 1: C++ if 문

// 사용자가 입력한 양수 출력
// 음수 입력 시 건너뜀
#include <iostream>
using namespace std;
int main() {
    int number;
    cout << "Enter an integer: ";
    cin >> number;
    // 숫자가 양수인지 검사
    if (number > 0) {
        cout << "You entered a positive integer: " << number << endl;
    }
    cout << "This statement is always executed.";
    return 0;
}

출력 1

Enter an integer: 5
You entered a positive number: 5
This statement is always executed.

사용자가 5 입력 시 number > 0이 true로 평가되어 if 본문 실행.

출력 2

Enter a number: -5
This statement is always executed.

-5 입력 시 조건이 false라 if 본문 실행 안 됨.


C++ if...else 문

if 문에 선택적 else 절을 둘 수 있습니다. 문법:

if (condition) {
    // 조건이 참일 때 실행할 코드
} else {
    // 조건이 거짓일 때 실행할 코드
}

if..else 문은 괄호 안의 condition을 평가합니다.

C++ 조건문 마스터하기: if, if-else, 중첩 if-else 완벽 해설

조건이 true면:

조건이 false면:


예제 2: C++ if...else 문

// 정수가 양수인지 음수인지 검사
// 이 프로그램은 0을 양수로 간주
#include <iostream>
using namespace std;
int main() {
    int number;
    cout << "Enter an integer: ";
    cin >> number;
    if (number >= 0) {
        cout << "You entered a positive integer: " << number << endl;
    } else {
        cout << "You entered a negative integer: " << number << endl;
    }
    cout << "This line is always printed.";
    return 0;
}

출력 1

Enter an integer: 4
You entered a positive integer: 4.
This line is always printed.

조건 number >= 0. 0 이상 입력 시 조건 true.

여기서 4 입력 → 조건 true → if 본문 실행.

출력 2

Enter an integer: -4
You entered a negative integer: -4.
This line is always printed.

-4 입력 → 조건 false → else 본문 실행.


C++ if...else if...else 문

if...else는 두 대안 중 하나를 실행합니다. 세 개 이상 대안에서 선택하려면 if...else if...else를 씁니다.

문법:

if (condition1) {
    // 코드 블록 1
} else if (condition2) {
    // 코드 블록 2
} else {
    // 코드 블록 3
}

동작:

C++ 조건문 마스터하기: if, if-else, 중첩 if-else 완벽 해설

참고: else if는 여러 개 둘 수 있지만 if와 else는 각각 하나만 가능.


예제 3: C++ if...else if...else

// 정수가 양수, 음수, 0인지 검사
#include <iostream>
using namespace std;
int main() {
    int number;
    cout << "Enter an integer: ";
    cin >> number;
    if (number > 0) {
        cout << "You entered a positive integer: " << number << endl;
    } else if (number < 0) {
        cout << "You entered a negative integer: " << number << endl;
    } else {
        cout << "You entered 0." << endl;
    }
    cout << "This line is always printed.";
    return 0;
}

출력 1

Enter an integer: 1
You entered a positive integer: 1.
This line is always printed.

출력 2

Enter an integer: -2
You entered a negative integer: -2.
This line is always printed.

출력 3

Enter an integer: 0
You entered 0.
This line is always printed.

사용자 입력을 받아 if...else if...else 사다리로 양수/음수/0 판별.


C++ 중첩 if...else

if 문 안에 또 다른 if 문을 쓰는 것을 중첩 if 문이라 합니다.

여러 겹의 if 문이라고 생각하면 됩니다. 바깥쪽(외부) if 문 안에 안쪽(내부) if 문이 있습니다. 문법:

// 외부 if 문
if (condition1) {
    // 문장들
    // 내부 if 문
    if (condition2) {
        // 문장들
    }
}

주의사항:


예제 4: C++ 중첩 if

// 중첩 if로 정수가 양수, 음수, 0인지 판별
#include <iostream>
using namespace std;
int main() {
    int num;
    cout << "Enter an integer: ";
    cin >> num;
    // 외부 if 조건
    if (num != 0) {
        // 내부 if 조건
        if (num > 0) {
            cout << "The number is positive." << endl;
        }
        // 내부 else 조건
        else {
            cout << "The number is negative." << endl;
        }
    }
    // 외부 else 조건
    else {
        cout << "The number is 0 and it is neither positive nor negative." << endl;
    }
    cout << "This line is always printed." << endl;
    return 0;
}

출력 1

Enter an integer: 35
The number is positive.
This line is always printed.

출력 2

Enter an integer: -35
The number is negative.
This line is always printed.

출력 3

Enter an integer: 0
The number is 0 and it is neither positive nor negative.
This line is always printed.

위 예제에서:

참고: 중첩 if...else는 로직을 복잡하게 만듭니다. 가능하면 피하는 게 좋습니다.


본문이 문장 하나뿐인 if...else

if...else 본문이 문장 하나뿐이면 { } 생략 가능. 예:

int number = 5;
if (number > 0) { cout << "The number is positive." << endl; }
else { cout << "The number is negative." << endl; }

다음과 같이 쓸 수 있습니다:

int number = 5;
if (number > 0) cout << "The number is positive." << endl;
else cout << "The number is negative." << endl;

두 프로그램 출력은 동일합니다.

참고: 본문이 한 문장이어도 { }를 쓰면 가독성이 좋아집니다.


더 알아보기

특정 상황에서는 삼항 연산자가 if...else를 대체할 수 있습니다. 자세히: C++ 삼항 연산자.

주어진 테스트 조건에 따라 여러 대안 중 선택해야 한다면 switch 문을 쓸 수 있습니다. 자세히: C++ switch.


더 많은 예제로 학습하기:

C 언어

  1. C# 조건문 완전 정복: if, if-else, if-else if, 중첩 if 문법과 예제
  2. C++ 클래스와 객체: 객체지향 프로그래밍 실전 가이드
  3. C++ 메모리 관리 마스터: new와 delete 전문가 활용법
  4. C++ 상속 접근 지정자: public, protected, private 완벽 이해
  5. C++ 프렌드 함수와 프렌드 클래스: 접근 제어 마스터하기
  6. 파이썬 문장, 들여쓰기, 주석: 명확한 가이드
  7. Java 중첩/내부 클래스 마스터: 종류, 예제, 모범 사례
  8. C++ 날짜와 시간 완벽 가이드: ctime 라이브러리 활용
  9. C++ 오버로딩 마스터하기: 함수 & 연산자 오버로딩 완전 정복
  10. C++ 파일 입출력 마스터하기: fstream으로 읽고 쓰기