컴퓨터 프로그래밍에서 if...else 문은 특정 조건 하에서 한 코드 블록을, 다른 조건 하에서 다른 코드 블록을 실행하기 위해 사용합니다.
예: 학생의 점수에 따라 등급(A, B, C) 부여
90점 초과 → A
75점 초과 → B
65점 초과 → C
C++에는 세 가지 형태의 if...else 문이 있습니다.
if 문
if...else 문
if...else if...else 문
C++ if 문
if 문의 문법:
if (condition) {
// if 문 본문
}
if 문은 괄호 ( ) 안의 condition을 평가합니다.
조건이 true면 if 본문 코드 실행
조건이 false면 if 본문 코드 건너뜀
참고:{ } 안의 코드가 if 문의 본문입니다.
예제 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을 평가합니다.
조건이 true면:
if 본문 실행
else 본문 건너뜀
조건이 false면:
else 본문 실행
if 본문 건너뜀
예제 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
}
동작:
condition1이 true면 코드 블록 1 실행
condition1이 false면 condition2 평가
condition2가 true면 코드 블록 2 실행
condition2가 false면 코드 블록 3 실행
참고: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) {
// 문장들
}
}
주의사항:
내부 if에 필요시 else, else if 추가 가능
내부 if를 외부 else나 else if 안에 넣을 수도 있음
여러 층으로 중첩 가능
예제 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.
위 예제에서:
사용자 입력을 num에 저장
if...else로 num이 0이 아닌지 검사
true면 내부if...else 실행
false면 외부else 실행 → "0은 양수도 음수도 아님" 출력
내부if...else는 입력이 양수인지(0 초과) 검사
true면 양수 출력
false면 음수 출력
참고: 중첩 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.