Using if/else statements allows for two-way decisions. What if we want to achieve additional selection options?
Answer: Use nested if/else statements, i.e., if/else statements within if/else statements.
Consider the example from the last lecture, but now suppose we have three sizes of drinks: S (Small) 75 cents, M (Medium) 85 cents, L (Large) 90 cents. Again, output the cost of the drink, assuming that the size of the drink is stored in the character variable object DrinkSize:
if (DrinkSize == 'S')
{
cout << "You have ordered a small drink." << endl;
cout << "Please pay 75 cents." << endl;
}//END IF
else
if (DrinkSize == 'M')
{
cout << "You have ordered a medium drink." << endl;
cout << "Please pay 85 cents." << endl;
}//END IF
else
{
cout << "You have ordered a large drink." << endl;
cout << "Please pay 90 cents." << endl;
}//END ELSE
As a second example use nested if/else statements to display appropriate
output:
If Grade is a or A then display:
Excellent.
Honor role student!
If Grade is b or B then display:
Good.
If Grade is c or C then display:
Fair.
If Grade is d or D then display:
Poor.
Try harder.
If Grade is f or F then display:
Fail.
Retake course.
Otherwise display:
ERROR: Invalid grade.
if ((Grade == 'a') || (Grade == 'A'))
{
cout << "Excellent." << endl;
cout << "Honor role student!" << endl;
}
else
if ((Grade == 'b') || (Grade == 'B'))
cout << "Good." << endl;
else
if ((Grade == 'c') || (Grade == 'C'))
cout << "Fair." << endl;
else
if ((Grade == 'd') || (Grade == 'D'))
{
cout << "Poor." << endl;
cout << "Try harder." << endl;
}
else
if ((Grade == 'f') || (Grade == 'F'))
{
cout << "Fail." << endl;
cout << "Retake course." << endl;
}
else
cout << "Error: Invalid Grade."
Note the indentation. An alternate, more elegant way to code this is
to use the
switch statement
switch (Grade)
case 'a':
case 'A': cout << "Excellent." << endl;
cout << "Honor role student!" << endl;
break;
case 'b':
case 'B': cout << "Good." << endl;
break;
case 'c':
case 'C': cout << "Fair." << endl;
break;
case 'd':
case 'D': cout << "Poor." << endl;
cout << "Try harder." << endl;
break;
case 'f':
case 'F': cout << "Fail." << endl;
cout << "Retake course." << endl;
break;
default: cout << "Error: Invalid Grade."
What if a break is omitted?Answer: The next sequential case is executed.
Suppose, in the above example all the breaks were omitted and Grade has the value 'C'. Then the output will be
Fair.
Poor.
Try harder.
Fail.
Retake course.
Clearly, this is not what we want to happen.