If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C programming, the "else if" statement is used to check multiple conditions in a single "if-else" statement. The syntax for "else if" is as follows:
Copy code
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition1 is false and condition2 is true
} else {
// code to be executed if condition1 and condition2 are both false
}
Here is an example of a program that uses "else if" to check the grade of a student based on their score:
Copy code
#include <stdio.h>
int main() {
int score;
printf("Enter your score: ");
scanf("%d", &score);
if (score >= 90) {
printf("Your grade is A.");
} else if (score >= 80) {
printf("Your grade is B.");
} else if (score >= 70) {
printf("Your grade is C.");
} else if (score >= 60) {
printf("Your grade is D.");
} else {
printf("Your grade is F.");
}
return 0;
}
In this example, the program prompts the user to enter their score, which is stored in the variable "score". The program then checks the score using a series of "else if" statements. If the score is greater than or equal to 90, the grade is "A". If the score is greater than or equal to 80 but less than 90, the grade is "B" and so on. If none of the conditions are met, the grade is "F".
You can also use logical operator &&
and ||
in else if for multiple conditions check.
Copy code
if (condition1 && condition2) {
// code to be executed if both condition1 and condition2 are true
} else if (condition3 || condition4) {
// code to be executed if either condition3 or condition4 is true
} else {
// code to be executed if none of the conditions are true
}
Comments: 0