If-else Statement

The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition. The syntax of the if-else statement is given below.

  1. if(expression){  
  2. //code to be executed if condition is true  
  3. }else{  
  4. //code to be executed if condition is false  
  5. }  

Flowchart of the if-else statement in C

if-else statement in c

Let's see the simple example to check whether a number is even or odd using if-else statement in C language.

  1. #include<stdio.h>    
  2. int main(){    
  3. int number=0;    
  4. printf("enter a number:");    
  5. scanf("%d",&number);     
  6. if(number%2==0){    
  7. printf("%d is even number",number);    
  8. }    
  9. else{    
  10. printf("%d is odd number",number);    
  11. }     
  12. return 0;  
  13. }    

Output

enter a number:4
4 is even number
enter a number:5
5 is odd number

Program to check whether a person is eligible to vote or not.

  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     int age;   
  5.     printf("Enter your age?");   
  6.     scanf("%d",&age);  
  7.     if(age>=18)  
  8.     {  
  9.         printf("You are eligible to vote...");   
  10.     }  
  11.     else   
  12.     {  
  13.         printf("Sorry ... you can't vote");   
  14.     }  
  15. }
Output:-
Enter your age?18
You are eligible to vote...
Enter your age?13
Sorry ... you can't vote