Else if Statements

A common programming construct is an if-else-if statement, sometimes called the if-else-if staircase because of its appearance. Its general form is

if(expression) statement;
 if(expression) statement;
 else statement;

Conditions are evaluated from top to bottom. As soon as a true condition is found, the statement attached to it is executed and the rest of the ladder is bypassed. If none of the conditions are correct, the final one is executed. This means that if all other conditional tests fail, the final statement is executed. If the final other is not present, no action is taken if all other conditions are false.

Although the statement is technically correct if the indentation of the previous one is correct, it leads to too deep indentation. For this reason, the if-otherwise statement is usually attached as follows:

 else if(expression)
 else if(expression)

Sample Program

#include <stdio.h>

int main() {
  int marks=66;
  if(marks>=90 && marks<=100)
   printf("Grade == AA");
  else if(marks>=80 && marks<90)
   printf("Grade == A+");
  else if(marks>=70 && marks<80)
   printf("Grade == A");
  else if(marks>=60 && marks<70)
   printf("Grade == B+");
  else if(marks>=50 && marks<60)
   printf("Grade == B");
  else if(marks>=40 && marks<50)
   printf("Grade == C+");
  else if(marks>=30 && marks<40)
   printf("Grade == C");
  else if(marks<30)
   printf("Grade == D");
  return 0;
else-if flow diagram