Nested if else statement

Nested if else statements are used to execute different piece of code when we have more than two options to handle.

Example

Grade selection based on score.

Here, if our score is more than 90, we will get S grade

If our score is in between 80 and 90, we will get A grade

If our score is in between 70 and 80, we will get B grade

If our score is in between 60 and 70, we will get C grade

If our score is in between 51 and 60, we will get D grade

If our score is 50, we will get E grade

Below 50 will be declared as U.

Here, we have more than 2 options to handle.




Syntax

Example

if(condition)
{
 
}
else if(condition)
{
 
}
else if(condition)
{
 
}
else
{
 
}


It will check each condition sequentially and once the condition succeeds it goes to the corresponding block.

If none of them are true, then else code part will take place.




Sample Program

Get score from the user and display the grade based on above logic.

Example

#include<stdio.h>

int main()
{
    int score;
    
    scanf("%d",&score);
    
    if(score <=100 && score >= 90) 
        printf("S");
    else if(score < 90 && score >= 80)
        printf("A");
    else if(score < 80 && score >= 70)
        printf("B");
    else if(score < 70 && score >= 60)
        printf("C");
    else if(score < 60 && score > 50)
        printf("D");
    else if(score == 50)
        printf("E");
    else if(score < 50 && score >= 0)
        printf("U");
    else
        printf("Enter a valid score between 0 and 100");
        
    return 0;
        
}