C Conditional Statement (if, if-else, if-elseif-else)

The Conditional statements are used to decide the flow of execution based on different conditions. If a condition is true, then the code can perform one action and if the condition is false, then it perform another action. In C language there are three conditional statements :

1. If statement
2. If...Else statement
3. If...Else if...Else statement

1. If statement :  

The If statement is used to execute a set of code when a condition is true. The syntax of If Statement is :
if (condition) {
  code to be executed if condition is true
}
Lets see an example of if statement.
#include <stdio.h>

int main() {
  int age = 0;
  printf("Enter your age : ");
  scanf("%d", &age);

  if(age < 18) {
    printf("You are a miner.\n");
  }

  if(age > 18) {
    printf("You are an adult.\n");
  }

  return 0;
}
If we give the number greater then or equal to18, then the output of program is :

Enter your age : 21
You are an adult.

And if we give the number below then 18, then

Enter your age : 15
You are a miner.


2. If...Else statement :

The If...Else statement allows to execute statements in a more controlled way. If the condition becomes true, execute block of code otherwise executes else block. The syntax of If...Else statement is :
if (condition) {
  code to be executed if condition is true
} else {
  code to be executed
}
Example C program :
#include <stdio.h>

int main() {
  int age = 0;
  printf("Enter your age : ");
  scanf("%d", &age);

  if(age < 18) {
    printf("You are a miner.\n");
  } else {
    printf("You are an adult.\n");
  }

  return 0;
}
Output :

Enter your age : 18
You are an adult.


3. If...Else if...Else statement :

The If...Else if...Else statement is allows to make a correct decision out of several conditions. Basically it evaluates the if condition and execute a block of code if expression become true, otherwise check the next else if condition and so on. If specified if...Else if condition does not satisfied, then the else block of code is executed. The Syntax is as follows :
if (condition_1) {
  code to be executed if condition is true
} else if (condition_2) {
  code to be executed if condition is true
} else if (condition_3) {
  code to be executed if condition is true
} else {
  code to be executed
}
Example C program :
#include <stdio.h>

int main() {
  int a, b;
  printf("Enter two number :\n");
  printf("1st Number : ");
  scanf("%d", &a);
  printf("2nd Number : ");
  scanf("%d", &b);
    
  if(a > b) {
    printf("%d is greater then %d\n", a, b);
  } else if(a < b) {
    printf("%d is less then %d\n", a, b);
  } else {
    printf("%d and %d is equal.\n", a, b);
  }

  return 0;
}
Output :

Enter two number :
1st Number : 20
2nd Number : 30
20 is less then 30


Next Topic :