The if
statement may have an optional else
block. The syntax of the if..else
statement is:
if (test expression) {
// run code if test expression is true
}
else {
// run code if test expression is false
}
How if…else statement works?
If the test expression is evaluated to true,
- statements inside the body of
if
are executed. - statements inside the body of
else
are skipped from execution.
If the test expression is evaluated to false,
- statements inside the body of
else
are executed - statements inside the body of
if
are skipped from execution.

Example 2: if…else statement
// Check whether an integer is odd or even
#include <stdio.h>
int main() {
int number;
printf("Enter an integer: ");
scanf("%d", &number);
// True if the remainder is 0
if (number%2 == 0) {
printf("%d is an even integer.",number);
}
else {
printf("%d is an odd integer.",number);
}
return 0;
}
Output
Enter an integer: 7 7 is an odd integer.
When the user enters 7, the test expression number%2==0
is evaluated to false. Hence, the statement inside the body of else
is executed.