Read this chapter, which reviews how computers make decisions using if statements. As you read this tutorial, you will understand that sometimes it is important to evaluate the value of an expression and perform a task if the value comes out to be true and another task if it is false. In particular, try the simulated program under the heading "Simulated Program" to see how a different response is presented to the user based on if a number is positive or negative.
Pay special attention to the "More Than One Statement per Branch" header to learn how the 'else' statement is used when there is more than one choice.
16. Three-way Decisions
Answer:
Enter the price:
100
Item cost: 100 Tax: 5.0 Total: 105.0
Three-way Decisions
An if
statement makes a two-way decision. Surely you must sometimes pick from more than just two branches?
We ran into this problem with a previous example program that divided integers into negative and non-negative. It really should pick one of three choices:
- Negative:
... -3 -2 -1
- Zero:
0
- Positive:
+1 +2 +3 ...
Two-way decisions can do this. First divide the integers into two groups (using a two-way decision):
- Negative:
... -3 -2 -1
- Zero and Positive:
0 +1 +2 +3 ...
Then further divide the second group (by using another two-way decision):
- Negative:
... -3 -2 -1
- Zero and Positive:
- Zero:
0
- Positive:
+1 +2 +3 ...
- Zero:
By repeatedly splitting groups into subgroups, you can split a collection into any number of fine divisions.
Question 16: