Worked question 15 - Programming Practice: Writing and Refining Programs
Kettle
14
Toaster
3
Write a program that:
- reads all the stock data from "stock.txt" into two parallel arrays, itemNames and quantities, keeping track of how many items were read in a variable itemCount
- includes a function called findItem that takes itemNames, itemCount and a search name as parameters, and returns the index of the item, or -1 if not found
- asks the user to input an item name to check
- uses findItem to look up the item and outputs its quantity, or a suitable message if the item is not found
- if the item is found and its quantity is less than 5, additionally outputs a low stock warning
Answer and mark scheme
Question 15
| Credit | Answer or working |
|---|---|
| B1 | correct file opened for reading and a condition-controlled loop that reads until WHILE NOT EOF(stockFile) becomes false |
| B1 | correct reading of a name line then a quantity line (cast to an integer with INT()) inside the loop, storing each into the respective array at index itemCount and incrementing itemCount (oe; accept declared fixed-size arrays with a running counter, or any other correct method of building the two arrays) |
| B1 | correct findItem function header taking the array, itemCount and searchName as parameters |
| B1 | correct iteration (e.g. FOR i = 0 TO itemCount - 1) and selection returning the matching index i inside the loop |
| B1 | correct RETURN of -1 placed after the loop, only reached if no match was found |
| B1 | correct INPUT for the search name, and a call to findItem storing the result in a variable |
| B1 | correct selection: IF index == -1 THEN a not-found message is output, ELSE quantities[index] is output |
| B1 | correct nested check, quantities[index] < 5, correctly nested inside the found branch, outputting a low stock warning when true |
- Answer:
itemCount = 0 DECLARE itemNames : ARRAY[0:49] OF STRING DECLARE quantities : ARRAY[0:49] OF INTEGER stockFile = OPENFILE("stock.txt", READ) WHILE NOT EOF(stockFile) itemNames[itemCount] = READFILE(stockFile) quantities[itemCount] = INT(READFILE(stockFile)) itemCount = itemCount + 1 ENDWHILECLOSEFILE(stockFile)FUNCTION findItem(itemNames, itemCount, searchName) FOR i = 0 TO itemCount - 1 IF itemNames[i] == searchName THEN RETURN i ENDIF NEXT i RETURN -1 ENDFUNCTION INPUT searchName index = findItem(itemNames, itemCount, searchName) IF index == -1 THEN OUTPUT "Item not found" ELSE OUTPUT quantities[index] IF quantities[index] < 5 THEN OUTPUT "Low stock warning" ENDIF ENDIF



