Saturday, 1 August 2015

Multiple if-else-if Statments :


if else if statement can be used to choose one block of statements from many blocks statements. It is used when there are many options but only one block can be executed on the basis of a condition. 

Syntax 


The syntax is as follows :

                if (condition)
                      block 1;
               else
               if (condition)
                     block 2;
               else 
               if (condition)
                     block 3;
                .
                .
                .
               else
                    block n;

Working :


When the first condition becomes true then first block gets executed.

When first condition becomes false then second block is checked against the condition. If second condition becomes true then second block gets executed.

if else if Flowchat :

Else if ladder

Example :

#include <iostream>
using namespace std;
 
int main ()
{
   // declare local variable
   int marks = 55;
 
   // check the condition
   if( marks >= 80 )
   {
       // if 1st condition is true
       cout << "U are 1st class !!" << endl;
   }
   else if( marks >= 60)
   {
       // if 2nd condition is false
       cout << "U are 2nd class !!" << endl;
   }
   else if( marks >= 40)
   {
       // if 3rd condition is false
       cout << "U are 3rd class !!" << endl;
   }
   else 
   {
       // none of condition is true
       cout << "U are fail !!" << endl;
   }
 
   return 0;
}

Output :

U are 3rd class !!

if-else Statements :


if else statement is another type of if statement. It executes one block of statements when the condition is true and the other when it is false. When the if condition becomes false then else block gets executed.

Conditions :


  • Both blocks can never be executed.
  • Both blocks can never be skipped.


Syntax 


if-else syntax is as follows :

             if (condition)
                 statement;
             else
                 statement;

Two or more statements are written in curly braces { }. The syntax is as follows :

             if (condition) {
                statements 1;
                statements 2;
                .
                .
               statements n;
                                    }
            else {
               statement 1;
               statement 2;
               .
               .
               statement n;
                    }

if else Flowchart :



if else in cpp


Example :

#include <iostream>
using namespace std;
 
int main ()
{
   // declare local variable
   int marks = 30;
 
   // check the condition
   if( marks > 40 )
   {
       // if condition is true
       cout << "You are pass !!" << endl;
   }
   else
   {
       // if condition is false
       cout << "You are fail !!" << endl;
   }
 
   return 0;
}

Output :

You are fail !!