11.3. Functions that make Decisions

Using if is essential for writing functions or procedures that need to make decisions. Say we want a function that calculates the cost to print pages in a library computer lab. The library charges $0.10 per page for up to 30 pages. If the number of pages is over 30, they charge $3.00 plus $0.05 per page over 30. The costForPrints function in the program below implements that logic.

Notice an additional advantage of putting our logic into a function (instead of at the top level of our program) - it is easier to use the code multiple times. In this case, it allows us to test how the if works for various values. We can call the function multiple times and pass different values for each function call. If we don’t use a function, we can only test one value each time we run the program.

Write the code for the function cabCost. It should calculate and return the cost a cab ride. If the distance traveled is less than or equal to 12 miles the cost is $2.00 a mile, and if the distance traveled is more than 12 miles the cost is $1.50 a mile.

You have attempted of activities on this page