C++

C++ Nested if문(중첩 if문) 총정리

김구티2 2024. 3. 10. 16:52

1. Nested if(중첩 if)문의 개념

중첩 if문은 if문 안에 또 다른 if문이 있는 개념이다. 조건 안의 조건을 구현하고자 할 때 Nested if문을 쓰는 것이다. C++에서는 임의의 중첩 수준을 허용한다.

 

구문: 

if(condition1)
{
    // Code to be executed 
    if(condition2)
    {
        // Code to be executed
    }
    else
    {
         // Code to be executed
    }
}
else
{
    // code to be executed
}

 

중첩 if else 문의 위 구문에서 내부 if else 문은 조건 1이 참이 되는 경우에만 실행되며, 그렇지 않으면 이 규칙은 내부 if else 문에 적용된다.

 

예시1에서 우리는 3개의 숫자 중 가장 큰 것을 확인할 것이다. 아래 예시에서 nested if else 문을 사용하여 주어진 3개의 숫자 중 가장 큰 숫자를 찾는 것이다. 

 

예시1:

// C++ Program to evaluate largest of the three numbers 
// using nested if else 
#include <iostream> 
using namespace std; 

int main() 

     // declaring three numbers 
     int a = 10; 
     int b = 2; 
     int c = 6; 

     // outermost if else 
     if (a < b) { 
          // nested if else 
           if (c < b) { 
                 printf("%d is the greatest", b); 
           } 
           else
                 printf("%d is the greatest", c); 
           } 
     } 
     else { 
           // nested if else 
           if (c < a) { 
                 printf("%d is the greatest", a); 
           } 
           else
                 printf("%d is the greatest", c); 
           } 
     } 

     return 0; 
}

 

출력:

10 is the greatest

 

예시2에서는 윤년을 확인해 본다. 그 해는 4로 나눠질 수 있고, 100으로 나눠질 수 있으며, 400으로 나눠질 수 있을 때 윤년이다. 그렇지 않으면 윤년이 아닌 것으로 한다. 

 

예시2:

// C++ program to check leap year using if-else 
#include <iostream> 
using namespace std; 

int main() 

     int year = 2024; 

     if (year % 4 == 0) { 
          // first nested if-else statement 
          if (year % 100 == 0) { 
                   // second nested if-else statement 
                   if (year % 400 == 0) { 
                         cout << year << " is a leap year."
                    } 
                    else
                         cout << year << " is not a leap year."
                    } 
          } 
               else
                    cout << year << " is a leap year."
          } 
     } 
    else
          cout << year << " is not a leap year."
     } 

     return 0; 
}

 

출력:

2024 is a leap year.

 

만약 input이 2023이라면

2023 is not a leap year이 나오게 된다.

728x90

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

C++ 점프문 총정리  (1) 2024.03.14
C++ 스위치 문 총정리  (1) 2024.03.12
C++ if else if 총정리  (0) 2024.03.10
C++ 조정자(Manipulator) 총정리  (0) 2024.03.10
C++ cerr 총정리  (0) 2024.03.10