The Else If Statement in C is very useful when we have to check several conditions. We can also use the Nested If statement to achieve the same but as the number of conditions increase, code complexity will also increase. Let us see the syntax of the Else if statement in C:
Else If Statement in C Syntax
The syntax of Else If statement in C Programming is as follows:
if (condition 1) statements 1 else if (condition 2) statements 2 else if (condition 3) statements 3 ........... else if (condition n) statements n else default statements
There will be some situations where condition 1, condition 2 is TRUE, for example:
x= 20, y=10
Condition 1: x > y //TRUE
Condition 2: x != y //TRUE
In these situations, statements under the Condition 1 will be executed because ELSE IF conditions will only be executed if it’s previous IF or ELSE IF statement fails.
Else If Statement in C Flow chart
The programming flow Chart behind this Else If Statement in C Programming is as shown below
Else If Statement in C Example
In this c else if program, User is asked to enter his total 6 subject marks. Using Else if statement in c we are going to calculate whether he is eligible for scholarship or not
CODE
/* Example for Else If Statement in C Language */ #include <stdio.h> int main() { int Totalmarks; //Imagine you have 6 subjects and Grand total is 600 printf("Please Enter your Total Marks\n" ); scanf( "%d", &Totalmarks ); if (Totalmarks >= 540) { printf("You are eligible for Full Scholarship\n"); printf("Congratulations\n"); } else if (Totalmarks >= 480) { printf("You are eligible for 50 Percent Scholarship\n"); printf("Congratulations\n"); } else if (Totalmarks >= 400) { printf("You are eligible for 10 Percent Scholarship\n"); printf("Congratulations\n"); } else { printf("You are Not eligible for Scholarship\n"); printf("We are really Sorry for You\n"); } }
OUTPUT 1: We are going to enter Totalmarks = 570. Here first If condition is TRUE
OUTPUT 2: This is to demonstrate the C Else IF statement. We are going to enter Totalmarks = 490 means first IF condition is FALSE. It will check the else if (Totalmarks >= 480), which is TRUE so it will print the statements inside this block. Although else if (Totalmarks >= 400) condition is TRUE, but it won’t check this condition.
OUTPUT 3: This time we are entering the Total marks as 401 means first IF condition, else if (Totalmarks >= 480) are FALSE. So, It will check the else if (Totalmarks >= 401), which is TRUE so it will print the statements inside this block.
OUTPUT 4: Let me enter Total marks = 380 means all the IF conditions Fail. So, It will print the statements inside the else block.
Thank You for Visiting Our Blog