What is if-else-if Ladder in C++?
The if-else-if ladder is used to check multiple conditions one by one. It is used when we have more than two choices and want to execute only one block of code.
In this, conditions are checked from top to bottom. As soon as one condition becomes true, its block executes and the rest are skipped.
Syntax of if-else-if Ladder:
if (condition1) {
// code
}
else if (condition2) {
// code
}
else if (condition3) {
// code
}
else {
// default code
}
Explanation:
- Conditions are checked one by one.
- If any condition is true, its block executes.
- Remaining conditions are skipped.
- If all conditions are false, the else block executes.
How if-else-if Ladder Works
- First, condition1 is checked.
- If false, then condition2 is checked.
- This process continues until a condition becomes true.
- Only one block executes.
Example of if-else-if Ladder
#include <iostream>
using namespace std;
int main() {
int marks = 82;
if (marks >= 90) {
cout << "Grade A";
}
else if (marks >= 75) {
cout << "Grade B";
}
else if (marks >= 50) {
cout << "Grade C";
}
else {
cout << "Fail";
}
return 0;
}
Output:
Grade B
Explanation:
- marks >= 90 → false
- marks >= 75 → true
- So, Grade B is printed and remaining conditions are skipped.
Important Points
- Used for multiple conditions.
- Conditions are checked in order.
- Only one block executes.
- else block is optional but recommended.
Summary:
- if-else-if ladder is used for multiple decision making.
- Conditions are checked one by one from top to bottom.
- Only the first true condition executes.