An if statement can be followed by an optional else statement, which executes when the Condition is false.
The if...else statement takes care of true as well as false conditions. It has two blocks. One block is for if and it is executed when the condition is true. The other block is of else and it is executed when the condition is false.
The else statement cannot be used without if. No multiple else statements are allowed with one if.
Syntax of if....else Statement:
if(condition) { // Statements inside body of if } else { //Statements inside body of else }
Flow Diagram
Fig- Flow Diagram of if-else Statement
Example:-
// Program to check whether an integer entered by the user is odd or even
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if 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.