C++ if..else...if Statement


Decision making is about deciding the order of execution of statements based on certain conditions or repeat a group of statements until certain specified conditions are met.

Decision making with if statement

The if statement may be implemented in different forms depending on the complexity of conditions to be tested.

The different forms are,

  1. Simple if statement
  2. If....else statement
  3. Nested if....else statement
  4. else if statement

if Statement

Syntax

if( expression )
{
 statement-inside;
}
 statement-outside;

If the expression is true, then 'statement-inside' it will be executed, otherwise 'statement-inside' is skipped and only 'statement-outside' is executed.

Example

#include< iostream.h>
int main( )
{
 int x,y;
 x=15;
 y=13;
 if (x > y )
 {
  cout << "x is greater than y";
 }
}
Output
x is greater than y

if...else Statement

Syntax

if( expression )
{
 statement1;
}
else
{
 statement2;
}

If the 'expression' is true, the 'statement1' is executed, else 'statement-block1' is skipped and 'statement2' is executed.

Example

#include< iostream.h>
void main( )
{
 int x,y;
 x=5;
 y=2;
 if (x > y )
 {
  cout << "x is greater than y";
 }
 else
 {
  cout << "y is greater than x";
 }
}
Ouput
x is greater than y

Nested if....else Statement

Syntax

if( expression )
{
     if( expression1 )
        {
                       statement1
         }
          else 
              {
                           statement2;
              }
}
else
{
 statement3;
}

if 'expression' is false the 'statement3' will be executed, otherwise it continues to perform the test for 'expression 1' .

If the 'expression 1' is true the 'statement1' is executed otherwise 'statement2' is executed.

Example
#include< iostream.h>
void main( )
{
 int a,b,c;
 cout << "enter 3 number"; 
cin >> a >> b >> c;
 if(a > b)
 {
  if(a > c)
  {
    cout << "a is greatest";
  }
  else 
  {
    cout << "c is greatest";
   } 
 } 
 else
  {
     if( b> c)
   {
     cout << "b is greatest";
   }
  else
   {
     cout << "c is greatest";
   }
  }
getch();
} 

else-if ladder

Syntax

if(expression 1)
{
 statement1;
}
else if(expression 2) 
{
 statement2;
}
else if(expression 3 ) 
{
 statement3;
}
else
{ 
 default-statement;
}

The expression is tested from the top(of the ladder) downwards. As soon as the true condition is found, the statement associated with it is executed.

Example

#include< iostream.h>
void main( )
{
 int a;
 cout  << "enter a number";  
 cin >>a;
 if( a= =1)
 {
  cout << "Sunday";
 }  
else if(a= =2 )
 {
    cout << "Monday";
 }
else if(a= =3)
 {
    cout << "Tuesday";
 }
 else 
 {
   cout << "Not Found";
 }
getch();
}

Share this article on