C if-else-if statement



if-else-if Statement OR else if Ladder :

Suppose we need to specify multiple conditions then we need to use multiple if statements like this –

void main ( )
{
    int num = 10 ;
    
    if ( num  >  0 )
        printf ("\n Number is Positive");
        
    if ( num  <  0 )
        printf ("\n Number is Negative");
        
    if ( num  ==  0 )
        printf ("\n Number is Zero");
}

which is not a right or feasible way to write program. Instead of this above syntax we use if-else-if statement.

Consider the Following Program –

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");
}

Explanation :

In the above program firstly condition is tested i.e number is checked with zero. If it is greater than zero then only first if statement will be executed and after the execution of if statement control will be outside the complete if-else statement.

else if ( num  <  0 )
        printf ("\n Number is Negative");

Suppose in first if condition is false then the second condition will be tested i.e if number is not positive then and then only it is tested for the negative.

else 
   printf ("\n Number is Zero");

and if number is neither positive nor negative then it will be considered as zero.

Which is faster and feasible way for Writing If ?

PointExample 1Example 2
No of If Statements32
No of times Condition Tested (Positive No.)31
No of times Condition Tested (Negative No.)32
No of times Condition Tested (Zero No.)32

Flowchart for If-Else Ladder :

else-if-else ladder in C Programming language