C++

C++ if else if 총정리

김구티2 2024. 3. 10. 13:10

1. if else if의 개념

C++에서 if-else-if 사다리는 사용자가 여러 옵션 중에서 선택할 수 있게 해주는 것이다. 아래의 그림을 통해 쉽게 이해할 수 있을 것이다.

그림에서 볼 수 있듯, ① if 문으로 들어가서 조건을 수행한 뒤, 그 조건이 거짓일 경우 ③ else if 문으로 들어가서 조건을 수행한다. 이때의 조건이 참이면 바로 블록을 탈출하게 되고, 또 거짓이라면 ⑤ 새로운 else if 문으로 다시 들어가서 조건을 수행하는 것이다. 그러고도 거짓일 경우 ⑥ else를 수행하게 된다.

 

예시1:

// C++ program to illustrate if-else-if ladder 
#include <iostream> 
using namespace std; 

int main() 

     int i = 20; 

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

     // Since i is not 10 
     // Check if i is 15 
     else if (i == 15) 
          cout << "i is 15"

     // Since i is not 15 
     // Check if i is 20 
     else if (i == 20) 
          cout << "i is 20"

     // If none of the above conditions is true 
     // Then execute the else statement 
     else
     cout << "i is not present"

     return 0; 
}

 

출력:

i is 20

 

예시2:

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

#include <iostream> 
using namespace std; 

int main() 

     int i = 25; 

     // Check if i is between 0 and 10 
     if (i >= 0 && i <= 10) 
          cout << "i is between 0 and 10" << endl; 

     // Since i is not between 0 and 10 
     // Check if i is between 11 and 15 
     else if (i >= 11 && i <= 15) 
         cout << "i is between 11 and 15" << endl; 

     // Since i is not between 11 and 15 
     // Check if i is between 16 and 20 
     else if (i >= 16 && i <= 20) 
          cout << "i is between 16 and 20" << endl; 

     // Since i is not between 0 and 20 
     // It means i is greater than 20 
     else
          cout << "i is greater than 20" << endl; 
}

 

출력:

i is greater than 20

728x90

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

C++ 스위치 문 총정리  (1) 2024.03.12
C++ Nested if문(중첩 if문) 총정리  (0) 2024.03.10
C++ 조정자(Manipulator) 총정리  (0) 2024.03.10
C++ cerr 총정리  (0) 2024.03.10
C++에서 cout 총정리  (0) 2024.03.09