Else If Statement in C



In this tutorial, we will learn about else-if statements in C. We will cover the basics of conditional execution using if-else-if statements.


What is an Else-If statement

An else-if statement is a conditional statement that allows multiple conditions to be tested sequentially. It provides a way to execute different code blocks based on different conditions.


Syntax

The syntax for the else-if statement in C is:

if (condition1) {
    // Code block to execute if condition1 is true
} else if (condition2) {
    // Code block to execute if condition2 is true
} else {
    // Code block to execute if none of the conditions are true
}

The else-if statement evaluates the specified conditions in order. The first condition that is true will have its code block executed; if none of the conditions are true, the code block inside the else statement is executed.

Flowchart of Else-If Statement


Example 1: Checking if a Number is Positive, Negative, or Zero

  1. Declare an integer variable num.
  2. Assign a value to num.
  3. Use an if-else-if statement to check if num is positive, negative, or zero.
  4. Print a message indicating whether num is positive, negative, or zero.

C Program

#include <stdio.h>
int main() {
    int num = -5;
    if (num > 0) {
        printf("%d is positive.\n", num);
    } else if (num < 0) {
        printf("%d is negative.\n", num);
    } else {
        printf("%d is zero.\n", num);
    }
    return 0;
}

Output

-5 is negative.


Example 2: Checking the Grade of a Student

  1. Declare an integer variable marks.
  2. Assign a value to marks.
  3. Use an if-else-if statement to check the grade based on the marks.
  4. Print a message indicating the grade.

C Program

#include <stdio.h>
int main() {
    int marks = 85;
    if (marks >= 90) {
        printf("Grade: A\n");
    } else if (marks >= 80) {
        printf("Grade: B\n");
    } else if (marks >= 70) {
        printf("Grade: C\n");
    } else if (marks >= 60) {
        printf("Grade: D\n");
    } else {
        printf("Grade: F\n");
    }
    return 0;
}

Output

Grade: B


Example 3: Checking the Temperature Range

  1. Declare a float variable temperature.
  2. Assign a value to temperature.
  3. Use an if-else-if statement to check the range of the temperature.
  4. Print a message indicating the temperature range.

C Program

#include <stdio.h>
int main() {
    float temperature = 75.5;
    if (temperature > 100) {
        printf("It's extremely hot.\n");
    } else if (temperature > 85) {
        printf("It's hot.\n");
    } else if (temperature > 60) {
        printf("It's warm.\n");
    } else if (temperature > 32) {
        printf("It's cold.\n");
    } else {
        printf("It's freezing.\n");
    }
    return 0;
}

Output

It's warm.