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."

C else-if statement – Questions and Answers

Q 1: What is the else-if ladder in C?

Ans: It allows checking multiple conditions sequentially.

Q 2: When is else-if used?

Ans: When more than two conditions need to be evaluated.

Q 3: Can we use multiple else-if blocks?

Ans: Yes, there is no fixed limit.

Q 4: What happens if one else-if condition becomes true?

Ans: The remaining conditions are skipped.

Q 5: Can else-if be used without else?

Ans: Yes, the final else block is optional.

C else-if statement – Objective Questions (MCQs)

Q1. What is the purpose of an else if ladder?






Q2. Which of the following is the correct syntax of an else-if ladder?






Q3. When is the else part executed in an else-if ladder?






Q4. What is the output of the following code?

int x = 0;
if (x > 0)
printf("Positive");
else if (x < 0)
printf("Negative");
else
printf("Zero");






Q5. How many else if statements can be used after an if?






Related C else-if statement Topics