12.3. Using Multiple if statements

You can use more than one if statement in your code. Here’s an example of a calculation that uses two if statements. Let’s compute the total cost of an item where the price is based on the weight of the item. If the item weighs less than 1 pound then the price is 1.45 a pound. If the item weighs 1 pound or more the price is 1.15 a pound.

Edit the code above and change the first line so that weight has a different value. Run it again and see what changes. Try it in the codelens as well to see how the different values for weight changes the lines of code that are executed.

In this second version, we set a price as a default, then change it only on the special condition. Does it work the same as the above example?

Mixed up programs

The following program should calculate the total price, but the lines are mixed up. The price is based on the weight. Items that weigh less than 2 pounds should cost 1.5. Items that weigh more than 2 pounds should cost 1.3. Drag the blocks from the left and place them in the correct order on the right. Be sure to also indent correctly! Click on <i>Check Me</i> to see if you are right. You will be told if any of the lines are in the wrong order or have the wrong indention.</p>

Write the code to calculate and print the cost of a 14 mile 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.

Show Comments

Note

Discuss topics in this section with classmates.

Show Comments
You have attempted of activities on this page