If else-if ladder Statement

The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario where there are multiple cases to be performed for different conditions. In if-else-if ladder statement, if a condition is true then the statements defined in the if block will be executed, otherwise if some other condition is true then the statements defined in the else-if block will be executed, at the last if none of the condition is true then the statements defined in the else block will be executed. There are multiple else-if blocks possible. It is similar to the switch case statement where the default is executed instead of else block if none of the cases is matched.

  1. if(condition1){  
  2. //code to be executed if condition1 is true  
  3. }else if(condition2){  
  4. //code to be executed if condition2 is true  
  5. }  
  6. else if(condition3){  
  7. //code to be executed if condition3 is true  
  8. }  
  9. ...  
  10. else{  
  11. //code to be executed if all the conditions are false  
  12. }  

Flowchart of else-if ladder statement in C

if-else-if ladder statement in c

The example of an if-else-if statement in C language is given below.

  1. #include<stdio.h>    
  2. int main(){    
  3. int number=0;    
  4. printf("enter a number:");    
  5. scanf("%d",&number);     
  6. if(number==10){    
  7. printf("number is equals to 10");    
  8. }    
  9. else if(number==50){    
  10. printf("number is equal to 50");    
  11. }    
  12. else if(number==100){    
  13. printf("number is equal to 100");    
  14. }    
  15. else{    
  16. printf("number is not equal to 10, 50 or 100");    
  17. }    
  18. return 0;  
  19. }    

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

Program to calculate the grade of the student according to the specified marks.

  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     int marks;   
  5.     printf("Enter your marks?");  
  6.     scanf("%d",&marks);   
  7.     if(marks > 85 && marks <= 100)  
  8.     {  
  9.         printf("Congrats ! you scored grade A ...");   
  10.     }  
  11.     else if (marks > 60 && marks <= 85)   
  12.     {  
  13.         printf("You scored grade B + ...");  
  14.     }  
  15.     else if (marks > 40 && marks <= 60)   
  16.     {  
  17.         printf("You scored grade B ...");  
  18.     }  
  19.     else if (marks > 30 && marks <= 40)   
  20.     {  
  21.         printf("You scored grade C ...");   
  22.     }  
  23.     else   
  24.     {  
  25.         printf("Sorry you are fail ...");   
  26.     }  
  27. }  

Output

Enter your marks?10
Sorry you are fail ...
Enter your marks?40
You scored grade C ...
Enter your marks?90
Congrats ! you scored grade A ...