![]() |
VOOZH | about |
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:
i is 20
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.
if (condition1) {
// Statements 1
}
else if (condition2) {
// Statements 2
}
else {
// Else body
}
where,
An if-else ladder can exclude else block.
The working of if else if ladder can be understood using the following flowchart:
The below examples demonstrate the common usage of if else if ladder in C++ programs:
Negative
As you may also have noticed, if the body contains only single statement, we can skip the braces {}.
Thursday