Multiple Selections:
Nested if
In the previous sections,
you learned how to implement one-way and two-way selections in a program. Some
problems require the implementation of more than two alternatives. For example,
suppose that if the checking account balance is more than $50000, the interest
rate is 7%; if the balance is between $25000 and $49999.99, the interest rate
is 5%; if the balance is between $1000 and $24999.99, the interest rate is 3%;
otherwise, the interest rate is 0%. This particular problem has four
alternatives—that is, multiple selection paths. You can include multiple
selection paths in a program by using an if...else
structure, if the action statement itself is an if or if...else statement. When one control statement is located
within another, it is said to be nested.
Assume that all variables
are properly declared, and consider the following statements:
if(score
>= 90) //Line 1
cout<<"The
grade is A"<<endl; //Line
2
else //Line 3
if(score >= 80) //Line 4
cout<<"The
grade is B"<<endl; //Line
5
else //Line
6
if(score >= 70) //Line 7
cout<<"The
grade is C"<<endl; //Line
8
else //Line 9
if(score >= 60) //Line 10
cout<<"The
grade is D"<<endl; //Line 11
else //Line 12
cout<<"The grade is F"<<endl; //Line 13
These statements illustrate
how to incorporate multiple selections using a nested if...else structure.
A nested if...else structure demands the answer to an important
question: How do you know which else is paired with which if? Recall that in C++
there is no stand-alone else statement. Every else must be paired with an if.
The rule to pair an else with an if is as
follows:
Pairing an else with an if: In a
nested if statement, C++ associates an else with the most recent incomplete if—that is, the most
recent if that has not been paired with an else.
Using this rule, in the
preceding example, the else at Line 3 is paired with the if
at Line 1. The else at Line 6 is paired with the if
at Line 4. The else at Line 9 is paired with the if
at Line 7, and the else at Line 12 is paired with the if at Line 10.
To avoid excessive
indentation, some programmers prefer to write the preceding code as follows:
if(score
>= 90)
cout<<"The
grade is A"<<endl;
else if(score >= 80)
cout<<"The
grade is B"<<endl;
else if(score >= 70)
cout<<"The
grade is C"<<endl;
else if(score >= 60)
cout<<"The
grade is D"<<endl;
else
cout<<"The
grade is F"<<endl;
The following examples will help you to see the various ways in which you can use nested if structures to implement multiple selection.