C if-else Statement

The if-else statement in C is used to perform the operations based on some specific condition. The operations specified in if block are executed if and only if the given condition is true.

There are the following variants of if statement in C language.

  • If statement
  • If-else statement
  • If else-if ladder
  • Nested if

If Statement

The if statement is used to check some given condition and perform some operations depending upon the correctness of that condition. It is mostly used in the scenario where we need to perform the different operations for the different conditions. The syntax of the if statement is given below.

  1. if(expression){  
  2. //code to be executed  
  3. }  

Flowchart of if statement in C

if statement in c

Let's see a simple example of C language if statement.

  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. return 0;  
  10. }    

Output

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

Program to find the largest number of the three.

  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     int a, b, c;   
  5.      printf("Enter three numbers?");  
  6.     scanf("%d %d %d",&a,&b,&c);  
  7.     if(a>b && a>c)  
  8.     {  
  9.         printf("%d is largest",a);  
  10.     }  
  11.     if(b>a  && b > c)  
  12.     {  
  13.         printf("%d is largest",b);  
  14.     }  
  15.     if(c>a && c>b)  
  16.     {  
  17.         printf("%d is largest",c);  
  18.     }  
  19.     if(a == b && a == c)   
  20.     {  
  21.         printf("All are equal");   
  22.     }  
  23. }  

Output

Enter three numbers?
12 23 34 
34 is largest