C else-if statement

An else if statement in C is used to check multiple conditions in sequence. It allows you to test more than two possibilities, making the program capable of choosing from more than just true or false.

Process flow:

  1. if checks the first condition.
  2. else if checks another condition if the previous ones were false.
  3. else provides a default action if none of the conditions are true.

Syntax:


if (condition1) {
    // Block of code executed if condition1 is true
} else if (condition2) {
    // Block of code executed if condition1 is false and condition2 is true
} else {
    // Block of code executed if none of the conditions are true
}

Example:


#include <stdio.h>

int main() {
   int number = -25;

    if (number > 0)
    {
        printf("The number is positive.");
    }
    else if (number < 0)
    {
        printf("The number is negative.");
    }
    else
    {
       printf("The number is zero.");
    }
    return 0;
}

Output:

The number is negative.

Explanation:

  1. First, the program checks if num > 0. If this is true, it would print "The number is positive."
  2. If the first condition is false, it checks the else if (num < 0). Since this is true, it prints "The number is negative."
  3. If neither condition is true, the else block will execute, printing "The number is zero."