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.