The if…else statement is a control flow statement in the C programming language that allows you to execute a block of code if a certain condition is true, and a different block of code if the condition is false. The syntax for an if…else statement is as follows:
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
For example, consider the following code:
int x = 10;
if (x > 5) {
printf("x is greater than 5\n");
} else {
printf("x is not greater than 5\n");
}
In this example, the condition is (x > 5), which is true because the value of x (10) is greater than 5. Therefore, the code inside the first block (the if block) will be executed and the message “x is greater than 5” will be printed to the console.
You can include an optional else if clause to check additional conditions. For example:
int x = 10;
if (x > 15) {
printf("x is greater than 15\n");
} else if (x > 5) {
printf("x is greater than 5 but not greater than 15\n");
} else {
printf("x is not greater than 5\n");
}
In this example, the first condition (x > 15) is false, so the code inside the first if block is not executed. The second condition (x > 5) is true, so the code inside the second if block is executed and the message “x is greater than 5 but not greater than 15” is printed to the console.
It is important to note that only one block of code will be executed in an if…else statement. Once a condition is found to be true, the code inside the corresponding block is executed and the rest of the statement is skipped. For example:
int x = 10;
if (x > 15) {
printf("x is greater than 15\n");
} else if (x > 5) {
printf("x is greater than 5 but not greater than 15\n");
} else {
printf("x is not greater than 5\n");
}
printf("This line will always be executed.\n");
In this example, the message “This line will always be executed.” will always be printed to the console, regardless of the value of x, because it is not part of any of the if…else blocks.