If…else if…else Statement

An if statement can be followed by an optional else if…else statement, which is very useful to test various conditions using single if…else if statement.

In If-else if statements, if ‘if’ condition is true then ‘if’ statement gets executed and if it is false then ‘else if’ condition is checked and if it is true then ‘else if’ gets executed otherwise condition moves to next statement and if all conditions are false then ‘else’ statement gets executed.

The syntax of an if…else if…else statement in C programming language is

if(boolean_expression 1) {
} else if( boolean_expression 2) {
} else if( boolean_expression 3) {
} else {
   statement n;

Code as an example of If…Else if…If statement

#include <stdio.h>
 int main () {

   /* local variable definition */
   int a = 50;
   if( a == 5 ) 
    printf("Value of a is 5\n" );
   else if( a == 15 ) 
   printf("Value of a is 15\n" );
   else if( a == 43 ) 
   printf("Value of a is 43\n" );
   printf("Value of a is: %d\n",a );
   return 0;

In the above code first of all ‘if’ condition will be checked, if a is 5, the condition will become false.

Then it will check first else if part in which a is 15 which is also false and will not be executed.

In third statement second else if will be checked in which a is 43 which is again false as a is set as 50 so the condition is again false.

Lastly the else part of the program will be executed which is default statement and has to be executed if all other statements are false.