Nested Conditional Statement
What if we need to check several conditions and if they are met, perform certain actions?
In this case we can use a
nested conditional statement.
A nested conditional statement is a conditional statement placed inside an
if
or
else
block. The
else
block always refers to the nearest preceding
if
block.
Problem
For the available amount of money (in conventional units) it is necessary to output the phrase:
- if the amount is more than 10 units, print "You have enough money";
- if the amount is more than 100 units, print "You have a lot of money";
- if the amount is less than 10 units, output "You don't have much money".
From the condition of the problem you can see that if you have more than 10 conditional units of money, you need to check the condition if it is more than 100 conditional units, and if it is more, then output the phrase "You have a lot of money". If the money is more than 10, but less than or equal to 100, then the phrase should be "You have enough money". It turns out that before you output this phrase, you need to check one more condition. An example implementation of a program with nested conditional statement is described below.
Program
#include <iostream>
using namespace std;
int main()
{
int money;
cin >> money;
if ( money > 10 ) # If the money is more than 10
{
# Nested conditional money
if ( money > 100 ) # and the money is more than 100
{
cout << "You have a lot of money" << endl; # Output 1 phrase
}
else
{
cout << "You have enough money" << endl; # If the money is more than 10,
# but not more than 100,
# then output phrase 2
}
}
else
{ # If the money is not more than 10, then output phrase 3.
cout << "You don't have much money" << endl;
}
return 0;
}
In this program
- We take an integer from the user as input and store it in the variable
money
.
- Then we use the
if...else
statement to check if the value of money
is greater than 10.
- If it is, we execute the inner
if...else
statement.
- If
false
, then the code in the outer else
statement is executed, which outputs the phrase "You don't have enough money."
- The inner
if...else
statement checks if the value of money
is greater than 100.
- If
true
, it outputs the phrase "You have a lot of money."
- If
false
, it outputs the phrase "You have enough money."
Don't forget to staircase the program, for better readability and better understanding!