C if…else if…else Statement

In this lesson, you will learn about the if…else if… else statement in C, its usage, and examples to better understand the topic.

if…else if… else Statement in C

Another Conditional Statement in C is the if..else if…else statement. It’s helpful if you are checking multiple conditions. 

if…else if…else Syntax in C

if (condition1) {
  // Block of Code will be processed if condition1 is true
}
else if(condition2) {
  // Block of Code will be processed if the condition1 is false and condition2 is true
} else {
  // Block of Code will processed if both condition1 and condition2 are false
}

if…else if…else Flowchart

 

Example of if…else if…else statement in C

Below is an example of the if…else if…else statement in C. The program takes two integer numbers from the users, then checks if the first number is less than, greater, or equal to the second number.

//C Program *** if...else if... else Statement ***
#include <stdio.h>

int main() {
  int var1, var2;
  printf("Please enter the 2 number: ");
  scanf("%d %d", & var1, & var2); // takes the input
  if (var1 > var2) {
    printf("%d is greater than %d.\n", var1, var2);
  } else if (var1 < var2) {
    printf("%d is less than %d.\n", var1, var2);
  } else {
    printf("%d is equal to %d.\n", var1, var2);
  }
  return 0;
}

Output

Please enter the 2 number: 5
7
5 is less than 7.

Another Example of if…else if..else Statemnet in C

The example below asks the user to input a day of the week as a number, then print out the name of the day based on hte user input.

//C Program *** if...else if... else Statement ***
#include <stdio.h>

int main() {
  int dayNum;
  printf("Please enter the a day (From 1 to 7: ");
  scanf("%d", & dayNum); // takes the input
  if (dayNum == 1) {
    printf("You entered %d, which is Monday.\n", dayNum);
  } else if (dayNum == 2) {
    printf("You entered %d, which is Tuesday.\n", dayNum);
  } else if (dayNum == 3) {
    printf("You entered %d, which is Wednesday.\n", dayNum);
  } else if (dayNum == 4) {
    printf("You entered %d, which is Thursday.\n", dayNum);
    } else if (dayNum == 5) {
    printf("You entered %d, which is Friday.\n", dayNum);
    } else if (dayNum == 6) {
    printf("You entered %d, which is Saturday.\n", dayNum);
    } else if (dayNum == 7) {
    printf("You entered %d, which is Sunday.\n", dayNum);
    } else {
    printf("Unknown Day");
  }
  return 0;
}

Output

Please enter the a day (From 1 to 7: 5
You entered 5, which is Friday.

In hte next lesso, you will learn about the switch case in C, which is another form of conditional stemements.