To show a multi-way decision based on several conditions, we use the else if statement.
This works by cascading of several comparisons. As soon as one of the conditions is true, the statement or block of statements following them is executed and no further comparisons are performed.
The syntax of Else If Statement in C Language
else if (condition_2)
else if (condition_n)
Here, the conditions are evaluated in order from top to bottom.
As soon as any condition evaluates to true, then the statement associated with the given condition is executed and control is transferred to Statements_x skipping the rest of the conditions following it. But if all conditions evaluate false, then the statement following final else is executed followed by the execution of Statements_x.
A program to illustrate Else If Statement in C Language
Write a program to award grades to students depending upon the criteria mentioned below:
- Marks less than or equal to 50 are given “D” grade
- Marks above 50 but below 60 are given “C” grade
- Marks between 60 to 75 are given “B” grade
- Marks greater than 75 are given “A” grade.
/* Program to award grades */
printf(“Enter the total marks of a student:\n”);
if (result <= 50)
else if (result <= 60)
else if (result <= 75)
Enter the total marks of a student: