Procedures, Functions, Arrays and File Handling: Question 8

Syllabus 8.2

Structured 6 marks

A library's catalogue stores 5 ISBN codes in a one-dimensional array, ISBNs, indexed from 1 to 5. The code below performs a linear search for a given Target ISBN, stopping as soon as a match is found.

DECLARE ISBNs : ARRAY[1:5] OF INTEGER
DECLARE Index : INTEGER
DECLARE Target : INTEGER
DECLARE Found : BOOLEAN

ISBNs[1] ← 4021
ISBNs[2] ← 4157
ISBNs[3] ← 3390
ISBNs[4] ← 4880
ISBNs[5] ← 4157

Index ← 1
Found ← FALSE
WHILE Index <= 5 AND Found = FALSE
    IF ISBNs[Index] = Target
        THEN
            Found ← TRUE
        ELSE
            Index ← Index + 1
    ENDIF
ENDWHILE

(a) State the value of ISBNs[3]. [1]

(b) Target is set to 4880 before the WHILE loop runs. Trace the WHILE loop for this value of Target, and state the final values of Index and Found once the loop stops. [3]

(c) Target is instead set to 9999, a value that does not appear anywhere in ISBNs. Trace the WHILE loop for this value of Target, and state the final values of Index and Found once the loop stops. [2]

Show worked solution Hide worked solution

Worked solution

Part (a): Reading a single array element

Arrays here are indexed from 1, so ISBNs[3] is the third value assigned: ISBNs[3] ← 3390. So ISBNs[3] = 3390. [1 mark]

Part (b): Tracing the search for Target = 4880

IndexFound (before check)ISBNs[Index]ISBNs[Index] = Target?Action
1FALSE4021NoIndex ← 2
2FALSE4157NoIndex ← 3
3FALSE3390NoIndex ← 4
4FALSE4880YesFound ← TRUE

After Found ← TRUE is set, the WHILE condition is rechecked: Index <= 5 is true (4 <= 5), but Found = FALSE is now false, so the compound condition as a whole is false and the loop stops immediately, without incrementing Index any further.

Final values: Index = 4, Found = TRUE. [3 marks]: [1] for correctly tracing steps at Index 1–3 (no match), [1] for identifying the match at Index 4, [1] for the correct final values of both Index and Found.

Part (c): Tracing the search for Target = 9999

IndexFound (before check)ISBNs[Index]ISBNs[Index] = Target?Action
1FALSE4021NoIndex ← 2
2FALSE4157NoIndex ← 3
3FALSE3390NoIndex ← 4
4FALSE4880NoIndex ← 5
5FALSE4157NoIndex ← 6

After Index becomes 6, the WHILE condition is rechecked: Index <= 5 is now false (6 <= 5 is false), so the loop stops. This time because the array has been fully searched, not because a match was found.

Final values: Index = 6, Found = FALSE. [2 marks]: [1] for correctly tracing to the end of the array with no match, [1] for the correct final values of both Index and Found.

Final answers

  • (a) ISBNs[3] = 3390
  • (b) Index = 4, Found = TRUE
  • (c) Index = 6, Found = FALSE