C if-else-if
In C, the if-else-if
statement is used to handle multiple conditions sequentially. It allows you to test multiple conditions one after the other until a true condition is found or until all conditions are tested. Once a true condition is encountered, the corresponding block of code associated with that condition is executed, and the program exits the entire if-else-if
structure. If none of the conditions is true, the code in the else
block (if provided) is executed.
Here's the general syntax of the if-else-if
statement in C:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else if (condition3) {
// Code to execute if condition3 is true
} else {
// Code to execute if none of the conditions is true
}
Here's an example of using if-else-if
to determine the day of the week based on a numeric input:
#include <stdio.h>
int main() {
int day;
printf("Enter a number (1-7): ");
scanf("%d", &day);
if (day == 1) {
printf("Sunday\n");
} else if (day == 2) {
printf("Monday\n");
} else if (day == 3) {
printf("Tuesday\n");
} else if (day == 4) {
printf("Wednesday\n");
} else if (day == 5) {
printf("Thursday\n");
} else if (day == 6) {
printf("Friday\n");
} else if (day == 7) {
printf("Saturday\n");
} else {
printf("Invalid input\n");
}
return 0;
}
In this example:
-
The program asks the user to input a number (1-7).
-
It uses the
if-else-if
structure to sequentially check which day corresponds to the input number. When it finds a match, it prints the corresponding day name.
-
If the input number does not match any of the conditions, the
else
block prints "Invalid input."
In this example, if the user entered the number 3
, and the program correctly determined that it corresponds to "Tuesday" and displayed "Tuesday" as the output.
Enter a number (1-7): 3
Tuesday
The if-else-if
structure allows you to handle multiple mutually exclusive conditions in a structured and efficient manner. It's particularly useful when you need to select one action out of several based on the outcome of multiple tests.