Last Updated : 02 Jan, 2025
In C++, the if-else-if ladder helps the user decide from among multiple options. The C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C++ else-if ladder is bypassed. If none of the conditions is true, then the final statement will be executed.
Let's take a look at an example:
C++
#include <iostream>
using namespace std;
int main() {
int i = 20;
// If - else ladder
if (i == 10)
cout << "i is 10";
else if (i == 15)
cout << "i is 15";
else if (i == 20)
cout << "i is 20";
else
cout << "i is not present";
return 0;
}
Explanation: In this program, compiler first checks if i is 10. Since i is not 10, it then moves to the next condition and checks if i is 15. Since i is also not 15, it checks if i is 20. Here the condition becomes true and the associated block is executed.
Syntax if-else-if Ladderif (condition1) {
// Statements 1
}
else if (condition2) {
// Statements 2
}
else {
// Else body
}
where,
An if-else ladder can exclude else block.
Working of the if-else-if LadderThe working of if else if ladder can be understood using the following flowchart:
Flowchart of if else if Ladder in C++The below examples demonstrate the common usage of if else if ladder in C++ programs:
Check whether a number is positive, negative or 0 C++
#include <iostream>
using namespace std;
int main() {
int n = -8;
// Check if the number is positive
if (n > 0)
cout << "Positive";
// Check if the number is negative
else if (n < 0)
cout << "Negative";
// If the number is neither positive nor negative
else
cout << "Zero";
return 0;
}
As you may also have noticed, if the body contains only single statement, we can skip the braces {}.
Print the day name using day number C++
#include <iostream>
using namespace std;
int main() {
int day = 4;
// Determine the day name using if-else if ladder
if (day == 1) {
cout << "Monday";
} else if (day == 2) {
cout << "Tuesday";
} else if (day == 3) {
cout << "Wednesday";
} else if (day == 4) {
cout << "Thursday";
} else if (day == 5) {
cout << "Friday";
} else if (day == 6) {
cout << "Saturday";
} else if (day == 7) {
cout << "Sunday";
} else {
cout << "Invalid day number";
}
return 0;
}
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4