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 ...

Assessment: Computer Science 0478 | Paper 2 Mock 01 | Algorithms, Programming and Logic Subject: Computer Science - 0478

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]

Answer Details

(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 i

The 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]

Download The App On Google Playstore

Everything you need to excel in your exams

Green Bridge CBT Mobile App
Personalized AI Learning Chat Assistant
200,000+ Exam Questions Across IGCSE, JAMB, WAEC & NECO
Over 3,900 Lesson Notes
Offline Support - Learn Anytime, Anywhere
Green Bridge Timetable
Literature Summaries & Potential Questions
Track Your Performance & Progress
In-depth Explanations for Comprehensive Learning