You are here

Multiway Selection using the Case Structure

19 January, 2016 - 11:41

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 l8 you can vote else if age equal to 39 you're middle aged else if age equal to 65 consider retirement else age is un-important

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. In some situations there is no default action. Consider this flowchart example:

media/image31.png
Figure 12.1 Flowchart example

This flowchart is of the case control structure and is used for multiway selection. The decision box holds the variable age. The logic of the case is one of equality where in the value in the variable age is compared to the listed values in order from left to right. Thus, the value stored in age is compared to 18 or is "age equal to 18". If it is true, the logic fows down through the action and drops out at the bottom of the case structure. If the value of the test expression is false, it moves to the next listed value to the right and makes another comparison. It works exactly the same as our nested if then else structure.