4.4 Nested if Statements | 175
else if(month == 3) // Nested if
monthName = "March";
else if(month == 4) // Nested if
else
monthName = "December";
This style prevents the indentation from marching continuously to the right. Even more im-
portantly, it visually conveys the idea that we are using a 12-way branch based on the vari-
able month.
It’s important to note one difference between the sequence ofifstatements and the
nestedifstructure: More than one alternative can be taken by the sequence ofifstatements,
but the nestedifcan select only one choice.To see why this difference is important, consider
the analogy of filling out a questionnaire. Some questions are like a sequence ofifstate-
ments, asking you to check all the items in a list that apply to you (such as all of your hob-
bies). Other questions ask you to select only one item in a list (your age group, for example)
and thus are like a nestedifstructure. Both kinds of questions occur in programming prob-
lems. Being able to recognize which type of question is being asked permits you to immedi-
ately select the appropriate control structure.
Another particularly helpful use of the nestedifis when you want to select from a se-
ries of consecutive ranges of values. For example, suppose that we want to display a message
indicating an appropriate activity for the outdoor temperature, given the following table:
Activity Temperature
Swimming Temperature > 85
Tennis 70 < Temperature ≤ 85
Golf 32 < Temperature ≤ 70
Skiing 0 < Temperature ≤ 32
Dancing Temperature ≤ 0
At first glance, you may be tempted to write a separate ifstatement for each range of tem-
peratures. On closer examination, however, it becomes clear that these conditions are in-
terdependent. That is, if one of the statements executes, none of the others should execute.
We really are selecting one alternative from a set of possibilities—just the sort of situation
in which we can use a nested ifstructure as a multiway branch. The only difference between
this problem and our earlier example of printing the month name from its number is that
we must check ranges of numbers in the ifexpressions of the branches.
With consecutive ranges, we can take advantage of that fact to make our code more efficient.
To do so, we arrange the branches in consecutive order by range.Then, if a particular branch has
been reached, we know that the preceding ranges have been eliminated from consideration.Thus,
theifexpressions must compare the temperature to only the lowest value of each range.
message = "The recommended activity is ";
if (temperature > 85)
message = message + "swimming.";