nested if else statement in c++

It is perfectly all right if we write an entire if...else construct within either the body of the if statement or the body of an else statement. This is called ‘nesting’of ifs.

Nested if...else statements has ability to control program flow based on multiple levels of condition.

Syntax

if(condition)
{
   // Statements inside body of if
}
else if(condition)
{
   //Statements inside body of else if
}
else 
{ 
     //Statements inside body of else 
}

Flow Diagram

Flow Diagram of nested if else statement

Example

// adifelse.cpp 
// demonstrates IF...ELSE with adventure program 
#include using namespace std; 
#include<conio.h>              //for getche() 

int main()
  { 
   char dir=’a’; 
   int x=10, y=10; 

   cout << “Type Enter to quit ”; 
   while( dir != ‘ ’ ) //until Enter is typed 
    { 
     cout << “ Your location is “ << x << “, “ << y; 
     cout << “ Press direction key (n, s, e, w): “;

     dir = getche(); //get character 
     if( dir==’n’) //go north 
        y--; 
    else 
      if( dir==’s’ ) //go south
         y++;
     else 
      if( dir==’e’ ) //go east 
        x++; 
      else if( dir==’w’ ) //go west 
        x--; 
   } //end while 
return 0; 
} //end main 

Output:

Your location is 10, 10 
Press direction key (n, s, e, w): n 
Your location is 10, 9 
Press direction key (n, s, e, w): e 
Your location is 11, 9 
Press direction key (n, s, e, w):