C if..else Statement


The if statement in C language is used to perform operation on the basis of condition. By using if-else statement , you can perform operation either condition is true or false.

There are many ways to use if statement in C language:

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

If Statement

The single if statement in C language is used to execute the code if condition is true.

Syntax

if(expression){  
//code to be executed  
}  

Example

#include <stdio.h>  
#include <conio.h>  
void main(){  
int num=0;  
clrscr();  
  
printf("enter a number:");  
scanf("%d",&num);  
  
if(number%2==0){  
printf("%d is even number",num);  
}  
  
getch();  
}  
Output
enter a number:2
2 is even number

If-else Statement

The if-else statement in C language is used to execute the code if condition is true or false.

Syntax

if(expression){  
//code to be executed if condition is true  
}else{  
//code to be executed if condition is false  
}  

Example

#include <stdio.h>  
#include <conio.h>  
void main(){  
int number=0;  
clrscr();  
  
printf("enter a number:");  
scanf("%d",&number);  
  
if(number%2==0){  
printf("%d is even number",number);  
}  
else{  
printf("%d is odd number",number);  
}  
getch();  
}
Output
enter a number:2
2 is even number

enter a number:3
3 is odd number

If else-if ladder Statement

The if else-if statement is used to execute one code from multiple conditions.

Syntax

if(condition1){  
//code to be executed if condition1 is true  
} else if(condition2){  
//code to be executed if condition2 is true  
}  
else if(condition3){  
//code to be executed if condition3 is true  
}  
...  
else{  
//code to be executed if all the conditions are false  
}

Example

#include <stdio.h>  
#include <conio.h>  
void main(){  
int num=0;  
clrscr();  
  
printf("enter a num:");  
scanf("%d",&number);  
  
if(num==10){  
printf("number is equals to 10");  
}  
else if(num==50){  
printf("number is equal to 50");  
}  
else if(num==100){  
printf("number is equal to 100");  
}  
else{  
printf("number is not equal to 10, 50 or 100");  
}  
getch();  
}  
Output
enter a number:7
number is not equal to 10, 50 or 100

enter a number:10
number is equal to 10

Share this article on