Question 1 Report
An array Names[1:20] stores the names of 20 students in a class. Some names may appear more than once if students share the same name.
(a) Write pseudocode for a function CountOccurrences that takes a name as a parameter and returns how many times it appears in the array. [3]
(b) Write pseudocode that uses CountOccurrences to find and output all names that appear more than once. Your solution should not output the same name twice. [4]
(c) State the output of CountOccurrences("Aisha") if "Aisha" appears at positions 3, 8, and 15. [1]
(a) The CountOccurrences function iterates through the entire array, comparing each element to the target name and incrementing a counter for each match: [3]
FUNCTION CountOccurrences(Target : STRING) RETURNS INTEGER
DECLARE Count : INTEGER
DECLARE i : INTEGER
Count ← 0
FOR i ← 1 TO 20
IF Names[i] = Target THEN
Count ← Count + 1
ENDIF
NEXT i
RETURN Count
ENDFUNCTION[1 mark for loop, 1 mark for comparison and counting, 1 mark for return]
(b) To find duplicates without reporting the same name twice, the algorithm checks earlier positions in the array. If the same name appears at a lower index, it has already been reported: [4]
DECLARE i : INTEGER
DECLARE j : INTEGER
DECLARE AlreadyReported : BOOLEAN
FOR i ← 1 TO 20
IF CountOccurrences(Names[i]) > 1 THEN
AlreadyReported ← FALSE
FOR j ← 1 TO i - 1
IF Names[j] = Names[i] THEN
AlreadyReported ← TRUE
ENDIF
NEXT j
IF AlreadyReported = FALSE THEN
OUTPUT Names[i], " appears ", CountOccurrences(Names[i]), " times"
ENDIF
ENDIF
NEXT iThe inner loop from 1 to i-1 checks whether Names[i] appeared earlier. If it did, this occurrence is a later duplicate and skipping it prevents the same name from being output more than once. [1 mark for checking count > 1, 1 mark for preventing duplicate output, 1 mark for checking earlier positions, 1 mark for correct output]
(c) CountOccurrences("Aisha") returns 3, because "Aisha" appears at positions 3, 8, and 15 in the array, giving a count of three matches. [1]
Everything you need to excel in your exams