Programming Fundamentals/Nested If Then Else

Overview

edit

Two-way selection structures may be nested inside other two-way selection structures, resulting in multi-way selection.

Discussion

edit

We are going to first introduce the concept of nested control structures. Nesting is a concept that places one item inside of another. Consider:

if expression
    true action
else 
    false action

This is the basic form of the if then else control structure. Now consider:

if age is less than 18
    you can't vote
    if age is less than 16
        you can't drive
    else
        you can drive
else 
    you can vote
    if age is less than 21
        you can't drink 
    else
        you can drink

As you can see we simply included as part of the “true action” a statement and another if then else control structure. We did the same (nested another if then else) for the “false action”. In our example, we nested if then else control structures. Nesting could have an if then else within a while loop. Thus, the concept of nesting allows the mixing of the different categories of control structures.

Multiway Selection

edit

One of the drawbacks of two-way selection is that we can only consider two choices. But what do you do if you have more than two choices? Consider the following which has four choices:

if age equal to 18
    you can now vote
else
    if age equal to 39
        you are middle-aged 
    else
        if age equal to 65
            you can consider retirement
        else
            your age is unimportant

You get an appropriate message depending on the value of age. The last item is referred to as the default. If the age is not equal to 18, 39 or 65 you get the default message. To simplify the code structure, this is most often written as:

if age equal to 18
    you can now vote
else if age equal to 39
    you are middle-aged 
else if age equal to 65
    you can consider retirement
else
    your age is unimportant

Key Terms

edit
multiway selection
Using control structures to be able to select from more than two choices.
nested control structures
Placing one control structure inside of another.

References

edit