Nested If Then Else

Kenneth Leroy Busbee

Overview

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

Discussion

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

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

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

License

Icon for the Creative Commons Attribution-ShareAlike 4.0 International License

Programming Fundamentals Copyright © 2018 by Kenneth Leroy Busbee is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book