Else If Statement In C Programmig





The "else if" statement is used in C programming to test multiple conditions. It allows you to specify a new condition to test if the preceding "if" statement or any previous "else if" statement evaluates to false.


Syntax

The syntax of the "else if" statement is as follows:

    if (condition1) {
      // code to execute if condition1 is true
    }
    else if (condition2) {
      // code to execute if condition2 is true
    }
    else {
      // code to execute if both condition1 and condition2 are false
    }


Example

Let's consider an example that determines the grade of a student based on their score:

#include <stdio.h>

int main() {
    int score;
    printf("Enter the score: ");
    scanf("%d", &score);
      
    if (score >= 90) {
    printf("Grade: A\n");
    }
    else if (score >= 80) {
    printf("Grade: B\n");
    }
    else if (score >= 70) {
    printf("Grade: C\n");
    }
    else if (score >= 60) {
      printf("Grade: D\n");
    }
    else {
        printf("Grade: F\n");
     }
      
    return 0;
}
Output:
Enter the score: 98
Grade: A
Enter the score: 86
Grade: B
Enter the score: 76
Grade: C
Enter the score: 69
Grade: D
Enter the score: 56
Grade: F

In this example, the program asks the user to enter a score. Based on the score, the program uses the "else if" statements to determine the corresponding grade and prints it on the screen.

If the score is greater than or equal to 90, the program prints "Grade: A". If the score is between 80 and 89, it prints "Grade: B", and so on. If none of the conditions are met, the program prints "Grade: F".

By using the "else if" statement, you can test multiple conditions and execute the corresponding code block based on the first condition that evaluates to true.