C++ Nested if Statements

C++ Nested if statements: In this statement, it will be targeting the another if statement. And in simple words, we can also say that if statement inside another if statement. You can easily place an if statement inside another if.

C++ Nested if statements Syntax

Syntax:

if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
// Executes when condition2 is true
}
}

Nested if statements Flow Chart

C++ Nested if Flow Chart

Nested if Statement Example:

#include<iostream>
using namespace std;
int main( )
{
int x =4, y =6, z=10;
 
cout<<"\nThe 3 numbers are:"<<x<<"\t"<<y<<"\t"<<z;
 
if(x > y)
{
  if(x > z)
   {
     cout<<"\nx is greatest";
 
    }
 
  else
  {
    cout<<"\nz is greatest";
   } 
  }
 else
 {
   if( y > z)
   {
     cout<<"\ny is greatest";
   }
  else
 {
   cout<<"\nz is greatest";
 }
}
 return 0;
}

Output:

The 3 numbers are: 4 6 10
z is greatest

Example 2

#include <iostream>
using namespace std;
int main() {
//local variable declaration:
  int a = 100;
  int b = 200; 
//check the boolean condition
  if( a == 100 ) {
//if condition is true then check the following
  if( b == 200 ) {
//if condition is true then print the following
 cout<<"Value of a is 100 and b is 200" << endl;
  }
 }
cout<<"Exact value of a is : " << a << endl;
   cout<<"Exact value of b is : " << b << endl;
 return 0;
}

Output:

Value of a is 100 and b is 200
Exact value of a is: 100
Exact value of b is: 200