C++ if else if Ladder
Last Updated :
11 Jan, 2024
Decision-making in C++ helps to write decision-driven statements and execute a particular set of code based on certain conditions.
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.
Syntax
if (condition)
statement 1;
else if (condition)
statement 2;
.
.
else
statement;
Working of the if-else-if ladder
- Control falls into the if block.
- The flow jumps to Condition 1.
- Condition is tested.
- If Condition yields true, goto Step 4.
- If Condition yields false, goto Step 5.
- The present block is executed. Goto Step 7.
- The flow jumps to Condition 2.
- If Condition yields true, goto step 4.
- If Condition yields false, goto Step 6.
- The flow jumps to Condition 3.
- If Condition yields true, goto step 4.
- If Condition yields false, execute else block. Goto Step 7.
- Exits the if-else-if ladder.
Flowchart if-else-if ladder
Examples of if else if the ladder
Example 1:
Below program illustrates the use if else if ladder in C++.
C++
#include <iostream>
using namespace std;
int main()
{
int i = 20;
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:
- Program starts.
- i is initialized to 20.
- condition 1 is checked. 20 == 10, yields false.
- condition 2 is checked. 20 == 15, yields false.
- condition 3 is checked. 20 == 20, yields true. “i is 20” gets printed.
- “Outside if-else-if” gets printed.
- Program ends.
Example 2:
Another example to illustrate the use of if else if ladder in C++.
C++
#include <iostream>
using namespace std;
int main()
{
int i = 25;
if (i >= 0 && i <= 10)
cout << "i is between 0 and 10" << endl;
else if (i >= 11 && i <= 15)
cout << "i is between 11 and 15" << endl;
else if (i >= 16 && i <= 20)
cout << "i is between 16 and 20" << endl;
else
cout << "i is greater than 20" << endl;
}
|
Output
i is greater than 20
Share your thoughts in the comments
Please Login to comment...