C++ else if statement

In C++, the else if condition is used to check multiple conditions in sequence. It provides an alternative to the if statement, allowing you to test more than one condition and execute the corresponding block of code based on which condition is true.

Syntax:


if (condition1) {
    // Code to execute if condition1 is true
} else if (condition2) {
    // Code to execute if condition2 is true
} else {
    // Code to execute if neither condition1 nor condition2 is true
}

Explanation:

  • if: Evaluates the first condition.
  • else if: Provides additional conditions to check if the previous if or else if conditions were false.
  • else: A fallback option if none of the previous conditions are true.

Example:


#include <iostream>
using namespace std;

int main() {
    int number = 25;

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

Output:

The number is positive.

If we pass number= -25 in the above code then Output will be

The number is negative.

If we pass number= 0 in the above code then Output will be

The number is zero.

C++ else if statement – Interview Questions

Q 1: What is else-if used for?
Ans: To check multiple conditions sequentially.
Q 2: Can there be multiple else-if blocks?
Ans: Yes.
Q 3: Is else mandatory after else-if?
Ans: No.
Q 4: How many conditions are executed?
Ans: Only the first true condition.
Q 5: Can else-if be used without if?
Ans: No.

C++ else if statement – Objective Questions (MCQs)

Q1. What is the use of else-if in C++?






Q2. What is the output of this code?

int x = 15;
if (x < 10)
cout << "Small";;
else if (x < 20)
cout << "Medium";
else
cout << "Large";






Q3. How many else-if statements can you use after an if statement?






Q4. In an else-if ladder, which block is executed?






Q5. What happens if none of the if or else-if conditions are true?






Related C++ else if statement Topics