Skip to main content

Section 14.9 Figuring out an Invoice

We can use variables to solve problems like those we might solve in a spreadsheet. Imagine that you had a spreadsheet with an invoice for an office supply company.
Figure 14.9.1. A spreadsheet with order information
Here’s a program to compute the total price for the invoice:
Listing 14.9.2.

Checkpoint 14.9.3.

    How many variables are in Listing 14.9.2?
  • 7
  • Yes, quantity1, unitPrice1, total1, quantity2, unitPrice2, total2, invoiceTotal.
  • 6
  • There are three variables per line, two lines, and one total.
  • 5
  • There are three variables per line, two lines, and one total.
  • 2
  • There are three variables per line, two lines, and one total.
We don’t really have to create new variables quantity2 and unitPrice2. We only use those to compute the total for the line, and then we could reuse those variable names.
Listing 14.9.4.

Checkpoint 14.9.5.

    How many variables are in Listing 14.9.4
  • 7
  • We have two fewer variables now.
  • 6
  • We have a total for each line (two), a quantity, a unitPrice, and an invoiceTotal.
  • 5
  • The variables are quantity, unitPrice, total1, total2, and invoiceTotal.
  • 2
  • We have a total for each line (two), a quantity, a unitPrice, and an invoiceTotal.
Let’s say that apples are $0.40 apiece, and pears are $0.65 apiece. Modify the program below to calculate the total cost (it should print 3.55).
You are welcome to try out the following answers by copying and pasting them into the program above before answering this question:

Checkpoint 14.9.6.

    Which line of code will compute the correct totalCost if put into the program above?
  • totalCost = numApples + numPears
  • That does not consider the cost of the apples or pears.
  • totalCost = (costPerApple * numApples) + (costPerPear * numPears)
  • We need to multiply the cost per apple times the number of apples and add it to the cost per pear times the number of pears.
  • totalCost = (costPerApple * numPears) + (costPerPear * numApples)
  • That gets the costs backwards
  • totalCost = (0.4 * numApples) + (0.65 + numPears)
  • That would work, but giving names to numbers makes code easier to understand.

Checkpoint 14.9.7.

Write the code to calculate and print how many paperclips you can buy if each paperclip is $0.05 and you have $4.00 in your pocket. It should print 80.
Create variables to hold each value. Calculate numPaperclips as budget / costPerClip. Be sure to print the result.
There is a hint available below. It doesn’t give the full answer, you will have to replace all of the ???’s in it with different values.
Hint.
# 1. DECLARE VARIABLES AND ASSIGN VALUES
costPerClip = ???
budget = ???
# 2. CALCULATE RESULT
numPaperclips = ??? / ???
# 3. PRINT RESULT
print(???)
You have attempted of activities on this page.