VOOZH about

URL: https://www.geeksforgeeks.org/cpp/cpp-nested-if-else-statement/

⇱ C++ Nested if-else Statement - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C++ Nested if-else Statement

Last Updated : 13 Feb, 2025

Nested if-else statements are those statements in which there is an if statement inside another if else. We use nested if-else statements when we want to implement multilayer conditions (condition inside the condition inside the condition and so on). C++ allows any number of nesting levels.

Let's take a look at a simple example:


Output
Divisible by 2 and 3

Explanation: In the above program, the outer if statement checks whether n is divisible by 2 and the inner if statement checks if n is divisible by 3. But as inner if is nested, the divisibly check with 3 is only performed if n is divisible by 2.

Basic Syntax of Nested if-else

The nesting of if-else depends on the situation but a general syntax can be defined as:

if(condition1) {
if(condition2) {
// Statement 1
}
else {
// Statement 2
}
}
else {
if(condition3) {
// Statement 3
}
else {
// Statement 4
}
}

In the above syntax of nested if-else statements, the inner if-else statement is executed only if 'condition1' becomes true otherwise else statement will be executed and this same rule will be applicable for inner if-else statements.

Flowchart of Nested if-else

👁 flowchart-of-nested-if-else-in-c

Examples of Nested if-else

The following C++ programs demonstrate the use of nested if-else statements.

Check the Greatest Among Three Numbers


Output
10

Check if the Given Year is a Leap Year

A year is a leap year if it follows the condition, the year should be evenly divisible by 4 then the year should be evenly divisible by 100 then lastly year should evenly divisible by 400 otherwise the year is not a leap year.


Output
2023 is not a leap year.
Comment
Article Tags:
Article Tags: