Conditional Statements in C

Conditional Statements in C

The conditional statement in C is all about “if” keyword . It looks like simple english language but holds a special meaning.

In C Programming conditional statements are possible through the following keywords and statements

  1. if statement
  2. if..else statement

IF statement

This statement is used to check between true conditions. When the statement is true then it executes what is inside the given statement otherwise it doesn’t execute . For example :

if(a>5){
      printf("a is greater than 5");
}

In the above example the output will be “a is greater than 5 ” only when the condition a>5 is true. In this case a>5 is condition and the rest is statement of if keyword. The overall program will be like this .

#include<stdio.h>
int main(){
   int a = 4,b = 9;
   if(a>5){
        printf("a = %d is greater than 5 ",a);
   }
   if(b==9){
        printf("%d is equal to 9 ",b);
   }
return 0;
}

In this case of if all the relational operators are used for conditions. And the output will be :

9 is equal to 9 

As in the above example the value of a is 4 and the condition is a>5 which is false so the statement “printf(“a = %d is greater than 5 “,a);” can not be executed . But another statement is executed as the value of b is 9 and the condition b==9 is true. So the statement “printf(“%d is equal to 9 “,b);” gets executed .

IF …ELSE statement

This statement is used to check between true and false conditions. When the statement is true then it executes what is inside the given statement otherwise it executes what is inside else statement. For example :

#include<stdio.h>
int main(){
    int age; 
    printf("Enter age of voters ");
    scanf("%d",&age);
    if(age >= 18){
         printf("the person can vote because the age is 18+ or 18 years");
    }else{
         printf("The person is not eligible to vote");
    }
return 0;
}

In the above example the output depends on the age provided by the user. Here scanf(“%d”, &age) is the code which will take user input . The keyword scanf scans the value provided by the user and it is stored at the variable age which is followed by %d as the datatype of age is integer. In this case &age is the address of age where the value given by the user is kept.

Share this on facebook

Subscribe to our Youtube Channel

Leave a comment

Your email address will not be published. Required fields are marked *