-->

If else ladder statement


The if else ladder statement in C programming language is used to test set of conditions in sequence. An if condition is tested only when all previous if conditions in if-else ladder is false. If any of the conditional expression evaluates to true, then it will execute the corresponding code block and exits whole if-else ladder.
Syntax of if else ladder statement
         if(expression_1)
            { 
            statement1; 
             } 
         else if (expression_2)
            { 
            statement2; 
           } 
         else if (expression_3) 
          { 
           statement3;
           } 
         else 
          { 
           statement4;
            }
First of all expression_1 is tested and if it is true then statement1 will be executed and control comes out out of whole if else ladder.
If expression_1 is false then only expression_2 is tested. Control will keep on flowing downward, If none of the conditional expression is true.
The last else is the default block of code which will gets executed if none of the conditional expression is true.

Flow chart



Example 1: C program that print number is positive or negative 
#include<stdio.h>
void main ( )
{
      int num = 10 ;  
      if ( num  >  0 )       
       printf ("\n Number is Positive"); 
      else if ( num  <  0 )     
       printf ("\n Number is Negative"); 
      else    
       printf ("\n Number is Zero");
}
Example 2: C program that print grade obtained by the  student in the exam
#include<stdio.h>
void main( )
 {
    int marks ;
    printf(" Enter the total  marks obtained by the student  in the exam  \n");
    scanf("%d",&marks);
      if ( marks  >  70 )       
       printf ("\n Distinction  or Grade A "); 
      else if ( num  > 60 )     
       printf ("\n First Class or Grade B");
       else if ( num  > 35 )     
       printf ("\n Second  Class or Grade C");
       else    
       printf ("\n Fail ");
}

  Next Topic 

No comments:

Post a Comment

Basic structure of c program