(^174) | Selection and Encapsulation
In general, any problem that involves a multiway branch(more than two alternative
courses of action) can be coded using nested ifstatements. For example, to store the name
of a month into a string variable, given its number, we could use a sequence of ifstatements
(unnested):
if (month == 1)
monthName = "January";
if (month == 2)
monthName = "February";
if (month == 3)
monthName = "March";
if (month == 12)
monthName = "December";
The equivalent nested ifstructure,
if (month == 1)
monthName = "January";
else
if (month == 2) // Nested if
monthName = "February";
else
if (month == 3) // Nested if
monthName = "March";
else
if (month == 4) // Nested if
is actually more efficient because it makes fewer comparisons. The first version—the se-
quence of independent ifstatements—always tests every condition (all 12 of them), even if
the first one is satisfied. In contrast, the nested ifsolution skips all remaining comparisons
after one alternative has been selected. As fast as modern computers are, many applica-
tions require so much computation that an inefficient algorithm can waste hours of com-
puter time. Always be on the lookout for ways to make your code more efficient, as long as
doing so doesn’t make it difficult for other programmers to understand. It’s usually better
to sacrifice a little efficiency for the sake of readability.
In the last example, notice how the indentation of thethenandelseclauses causes the state-
ments to move continually to the right. Alternatively, we can use a special indentation style with
deeply nestedif-elsestatements to indicate that the complex structure is just choosing one of
a set of alternatives. This general multiway branch is known as anif-else-ifcontrol structure:
if (month == 1)
monthName = "January";
else if(month == 2) // Nested if
monthName = "February";
やまだぃちぅ
(やまだぃちぅ)
#1