Question 1 Report
A program uses a sentinel value to control input into an array.
DECLARE Numbers : ARRAY[1:20] OF INTEGER
DECLARE Count : INTEGER
DECLARE Value : INTEGER
Count <- 0
OUTPUT "Enter numbers (-1 to stop):"
INPUT Value
WHILE Value <> -1 AND Count < 20
Count <- Count + 1
Numbers[Count] <- Value
INPUT Value
ENDWHILE
OUTPUT Count, " numbers entered"
(a) State what a sentinel value is, using this example. [2]
(b) If the user enters: 15, 8, 42, 3, -1, state the contents of the array and the value of Count. [2]
(c) Explain the purpose of the condition Count < 20 in the WHILE loop. [2]
(d) Write pseudocode to extend the program so it also calculates and outputs the average of the numbers entered (after the loop). [2]
(e) State one advantage of using a sentinel value compared to asking the user in advance how many numbers they want to enter. [1]
(a) A sentinel value is a special value that signals the end of data input, rather than being part of the actual data. [1] In this example, -1 is the sentinel. When the user enters -1, the WHILE loop condition Value <> -1 becomes false, causing the loop to exit. The value -1 itself is never stored in the array because the check happens before the assignment. [1]
(b) If the user enters 15, 8, 42, 3, -1: [2]
Array contents: Numbers[1]=15, Numbers[2]=8, Numbers[3]=42, Numbers[4]=3 [1]
Count = 4 [1]
The sentinel value -1 terminates the loop and is not stored. Positions 5-20 remain unchanged (uninitialised).
(c) Purpose of Count < 20 in the WHILE loop: [2]
It prevents the array from overflowing by ensuring no more than 20 values can be stored. [1] Without this guard, if the user enters more than 20 values without typing -1, the program would attempt to write to Numbers[21], which is beyond the array bounds and would cause a runtime error (array index out of bounds). [1]
(d) Pseudocode to calculate and output the average after the loop: [2]
IF Count > 0
THEN
DECLARE Total : INTEGER
Total <- 0
FOR Index <- 1 TO Count
Total <- Total + Numbers[Index]
NEXT Index
OUTPUT "Average: ", Total / Count
ENDIF[1] for calculating the total using a loop that runs to Count (not to 20, which would include uninitialised values), [1] for dividing by Count and handling the edge case where Count = 0 (division by zero).
(e) Advantage of a sentinel value over pre-specifying the count: [1]
The user does not need to know in advance how many numbers they will enter. [1] They can enter as many or as few values as needed and simply type the sentinel value when finished. This is more flexible and user-friendly, especially when the number of items is not known beforehand.
Everything you need to excel in your exams