visit us: www.5square.in

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. The syntax of if statement is given below:

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

    Flowchart of if statement in C


    simple example of c language if statement.
    #include <stdio.h>  
    void main(){  
    int num=0;  
    printf("enter a num:");  
    scanf("%d",&num); 
    if(num%2==0){  
    printf("%d is even num",num);  
      }
      }  
    Output:
    enter a num:  12
    12 is even num
    

    If-else Statement

    The if-else statement in C language is used to execute the code if condition is true or false. The syntax of if-else statement is given below:
    if(expression){  
         //code to be executed if condition is true  
       }   else    {  
           //code to be executed if condition is false  
     }

    Flowchart of if-else statement in C



    Let's see the simple example of even and odd number using if-else statement in C language.

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

    If else-if ladder Statement

    The if else-if statement is used to execute one code from multiple conditions. The syntax of if else-if statement is given below:

    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  
     }  
    

    Flowchart of else-if ladder statement in C


    The example of if-else-if statement in C language is given below.

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