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  


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


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  


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




Jay Kakadiya

Jay Kakadiya Creator

I am a computer field, & i am Web developer.

Suggested Creators

Jay Kakadiya