Question 1 Report
A vending machine sells three items:
| Code | Item | Price (pence) |
|---|---|---|
| A | Drink | 120 |
| B | Crisps | 85 |
| C | Chocolate | 100 |
The machine accepts coins of 10p, 20p, 50p and 100p. The user inserts coins until enough money is entered, then selects an item. The machine dispenses the item and gives change.
(a) Write pseudocode for this vending machine algorithm. Your solution must:
[8]
(b) Trace through your algorithm for the following inputs: coins 50p, 50p, 50p; selection "B". [3]
(c) State the change that should be given. [1]
(a) The vending machine algorithm collects coins, validates them, accepts an item selection, and calculates change. [8]
DECLARE TotalInserted : INTEGER
DECLARE Coin : INTEGER
DECLARE Selection : CHAR
DECLARE Price : INTEGER
DECLARE Change : INTEGER
DECLARE ValidCoin : BOOLEAN
TotalInserted ← 0
REPEAT
REPEAT
OUTPUT "Insert coin (10, 20, 50, 100) or 0 to select item: "
INPUT Coin
ValidCoin ← (Coin = 10 OR Coin = 20 OR Coin = 50 OR Coin = 100 OR Coin = 0)
IF ValidCoin = FALSE THEN
OUTPUT "Invalid coin"
ENDIF
UNTIL ValidCoin = TRUE
IF Coin <> 0 THEN
TotalInserted ← TotalInserted + Coin
OUTPUT "Total: ", TotalInserted, "p"
ENDIF
UNTIL Coin = 0
REPEAT
OUTPUT "Select item (A, B, C): "
INPUT Selection
UNTIL Selection = 'A' OR Selection = 'B' OR Selection = 'C'
CASE OF Selection
'A': Price ← 120
'B': Price ← 85
'C': Price ← 100
ENDCASE
IF TotalInserted < Price THEN
OUTPUT "Insufficient funds. You inserted ", TotalInserted, "p. Price is ", Price, "p"
ELSE
Change ← TotalInserted - Price
OUTPUT "Dispensing item"
IF Change > 0 THEN
OUTPUT "Change: ", Change, "p"
ENDIF
ENDIFThe inner loop validates each coin before accepting it [1]. The outer loop accumulates the total until the user enters 0 [1]. The CASE statement maps the selection to its price [1]. Change is computed as the difference between the amount inserted and the price [1].
(b) Trace for coins 50p, 50p, 50p and selection "B": [3]
| Step | Action | TotalInserted |
|---|---|---|
| 1 | Insert 50p (valid) | 50 |
| 2 | Insert 50p (valid) | 100 |
| 3 | Insert 50p (valid) | 150 |
| 4 | Enter 0 to finish coins | 150 |
| 5 | Select "B", Price = 85 | 150 |
| 6 | Change = 150 - 85 = 65 | 150 |
Output: "Dispensing item" followed by "Change: 65p" [1].
(c) The change is 65p [1].
Everything you need to excel in your exams