< previous page page_210 next page >

Page 210
In general, any problem that involves a multi-way branch (more than two alternative courses of action) can be coded using nested If statements. For example, to print out the name of a month given its number, we could use a sequence of If statements (unnested):
if (month == 1)
    cout << January;
if (month == 2)
    cout << February;
if (month == 3)
    cout << March;
  .
  .
  .
if (month == 12)
    cout << December;
But the equivalent nested If structure,
if (month == 1)
    cout << January;
else
    if (month ==2)          // Nested If
        cout << February;
    else
        if (month == 3)          // Nested If
            cout << March;
        else
            if (month == 4)          // Nested If
              .
              .
              .
is more efficient because it makes fewer comparisons. The first versionthe sequence of independent If statementsalways tests every condition (all 12 of them), even if the first one is satisfied. In contrast, the nested If solution skips all remaining comparisons after one alternative has been selected.
In the last example, notice how the indentation of the thenand elseclauses causes the statements to move continually to the right. We use a special indentation style with deeply nested If-Then-Else statements to indicate that the complex structure is just choosing one of a set of alternatives. This general multi-way branch is known as an If-Then-Else-Ifcontrol structure:
if (month == 1)
    cout << January;

 
< previous page page_210 next page >