C++

C++ if else문 총정리

김구티2 2024. 3. 8. 19:20

1. if else문의 개념

if문은 조건이 참이면 문장 블록을 실행하고, 조건이 거짓이면 실행하지 않는다는 것으로 그친다. 그러나 조건이 거짓일 경우 다른 것을 수행하려면 어떻게 해야 할까? 이때 등장하는 것이 if else다. 조건이 거짓일 때 코드 블록을 실행하기 위해 if문과 함께 다른 문장이 사용될 수 있다.

 

2에서 if문이 실행되는데, if가 참이면 우리가 알던 것처럼 if문 내의 블록이 그대로 수행된다. 그런데 여기서 else가 존재하므로, if문이 거짓일 경우 else 블록을 넘어가 else 안에 있는 내용이 수행된다.

 

구문:

if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}

 

2. if else문의 예시

예시1:

// C++ program to illustrate if-else statement 

#include <iostream> 
using namespace std; 

int main() 

     int i = 20; 

     // Check if i is 10 
     if (i == 10) 
          cout << "i is 10"

     // Since is not 10 
     // Then execute the else statement 
     else
          cout << "i is 20\n"

     cout << "Outside if-else block"

     return 0; 

 

출력:

i is 20
Outside if-else block

 

프로그램이 시작된다. i의 초기값은 20으로 입력되었다. if문에서 i==10인 조건을 달았으므로, 조건은 거짓이 된다. 따라서 바로 else로 넘어가서 i is 20이 출력되고, 이후 if문을 모두 탈출하여 Outside if-else block이 출력된다.

 

예시2:

// C++ program to illustrate if-else statement 

#include <iostream> 
using namespace std; 

int main() 

     int i = 25; 

     if (i > 15) 
          cout << "i is greater than 15"; 
     else
          cout << "i is smaller than 15"

     return 0; 
}

 

출력:

i is greater than 15

 

i는 초기값 25로 저장되었고, if문에 들어간다. i>15라는 조건이 참이기 때문에 if문은 수행되며, else문은 수행되지 않고 블록을 탈출한다.

728x90

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

C++에서 cin 총정리  (0) 2024.03.09
C++ 연산자(Operator) 총정리  (0) 2024.03.09
C++ if문 총정리  (0) 2024.03.08
C++ 데이터 타입 총정리  (0) 2024.02.21
C++ 리터럴(Literals) 총정리  (0) 2024.02.20