C – If..else, Nested If..else and else..if Statement

C If else statement

Syntax of if else statement:
If condition returns true then the statements inside the body of “if” are executed and the statements inside body of “else” are skipped.
If condition returns false then the statements inside the body of “if” are skipped and the statements in “else” are executed.

if(condition) {
   // Statements inside body of if
}
else {
   //Statements inside body of else
}

Flow diagram of if else statement

C If else flow diagram

C Nested If..else statement

When an if else statement is present inside the body of another “if” or “else” then this is called nested if else.
Syntax of Nested if else statement:

if(condition) {
    //Nested if else inside the body of "if"
    if(condition2) {
       //Statements inside the body of nested "if"
    }
    else {
       //Statements inside the body of nested "else"
    }
}
else {
    //Statements inside the body of "else"
}

C – else..if statement

The else..if statement is useful when you need to check multiple conditions within the program, nesting of if-else blocks can be avoided using else..if statement.

Syntax of else..if statement:

if (condition1) 
{
   //These statements would execute if the condition1 is true
}
else if(condition2) 
{
   //These statements would execute if the condition2 is true
}
else if (condition3) 
{
   //These statements would execute if the condition3 is true
}
.
.
else 
{
   //These statements would execute if all the conditions return false.
}

Important Points:
1. else and else..if are optional statements, a program having only “if” statement would run fine.
2. else and else..if cannot be used without the “if”.
3. There can be any number of else..if statement in a if else..if block.
4. If none of the conditions are met then the statements in else block gets executed.
5. Just like relational operators, we can also use logical operators such as AND (&&), OR(||) and NOT(!).