Procedures, Functions, Arrays and File Handling: Computer Science 0478 (Cambridge O Level / IGCSE)

Syllabus 8.1, 8.2, 8.3 · Strand 8 Programming

Questions
10
Total marks
45
Tier mix
10 Core

0 of 10 questions completed

Quick-fire this topic Practice set

Syllabus coverage

  • 8.1 5 questions
  • 8.2 5 questions
  • 8.3 2 questions

Once a program grows beyond a few lines, splitting it into named, reusable blocks makes it far easier to write, test and maintain. A procedure or function is defined once, at the start of the code, and can then be called with up to three parameters each time its behaviour is needed, with a function additionally returning a value (syllabus 8.1). Variables declared inside one of these blocks are local and disappear once it finishes, while global variables are visible throughout the whole program, a distinction that matters for both correctness and for writing readable code with meaningful identifiers and library routines such as ROUND and RANDOM.

An array (8.2) stores a fixed-size collection of related values under one identifier, addressed by an index that, again, may start at zero or one; a one-dimensional array models a simple list while a two-dimensional array models a grid, and both are commonly filled or read using iteration, including loops nested inside one another. File handling (8.3) extends storage beyond a single run of the program: a file can be opened for reading or writing, used to store single items of data or whole lines of text, and then closed, giving a program a way to keep data permanently rather than losing it when it ends.

The exam-style questions below are original, written to match this syllabus objective, and each is followed by a full worked solution so you can check your method step by step.

Question 1

Multiple choice 1 mark

A program uses a global variable, TicketsSold, and a procedure that declares its own local variable with the identical identifier, to record how many cinema tickets have been sold.

DECLARE TicketsSold : INTEGER
TicketsSold ← 10

PROCEDURE ResetCounter()
    DECLARE TicketsSold : INTEGER
    TicketsSold ← 0
    OUTPUT TicketsSold
ENDPROCEDURE

CALL ResetCounter()
OUTPUT TicketsSold

What is displayed, in order, by the two OUTPUT statements above?

Question 2

Structured 5 marks

A zoo uses a function, EntryFee, to calculate the entry price, in dollars, for one visitor of a given age, Age. The rules are:

  • age under 3: a fee of 0.00
  • age 3 to 12 inclusive: a fee of 5.50
  • age 13 and over: a fee of 9.75

Part of the pseudocode for this function is shown below, with one line missing.

FUNCTION EntryFee(Age : INTEGER) RETURNS REAL
    DECLARE Fee : REAL
    IF Age < 3
        THEN
            Fee ← 0.00
        ELSE
            IF Age <= 12
                THEN
                    Fee ← 5.50
                ELSE
                    Fee ← 9.75
            ENDIF
    ENDIF
    // missing line (i)
ENDFUNCTION

(a) State the missing line of pseudocode, labelled (i), that must appear immediately before ENDFUNCTION so the function correctly sends back the value it has calculated. [1]

(b) The main program declares a global variable, TotalTaken, and calls the function twice, as shown below.

DECLARE TotalTaken : REAL
TotalTaken ← 0
TotalTaken ← TotalTaken + EntryFee(8)
TotalTaken ← TotalTaken + EntryFee(15)
OUTPUT TotalTaken

Trace this code and state the value output for TotalTaken. [2]

(c) Age and Fee are both local to the function EntryFee, while TotalTaken is global. Describe the difference between a local variable and a global variable, referring to Fee and TotalTaken in your answer. [2]

Question 3

Structured 7 marks

A fitness app stores the number of steps a user walked on each of 6 days of the week in a one-dimensional array, StepCounts, indexed from 1 to 6, where index 1 represents Monday and index 6 represents Saturday.

DECLARE StepCounts : ARRAY[1:6] OF INTEGER
DECLARE Day : INTEGER
DECLARE Total : INTEGER

StepCounts[1] ← 4200
StepCounts[2] ← 6100
StepCounts[3] ← 3950
StepCounts[4] ← 7300
StepCounts[5] ← 5800
StepCounts[6] ← 6650

Total ← 0
FOR Day ← 1 TO 6
    Total ← Total + StepCounts[Day]
NEXT Day

(a) State the value of StepCounts[4]. [1]

(b) Trace the FOR loop and state the value of Total once it has finished running. [2]

(c) A function, MostActiveDay, is used to find the index of the day with the highest number of steps. Complete the pseudocode below by writing the pseudocode statement missing at each of the two lines labelled (i) and (ii).

FUNCTION MostActiveDay(Steps : ARRAY[1:6] OF INTEGER) RETURNS INTEGER
    DECLARE Best : INTEGER
    DECLARE Day : INTEGER
    Best ← 1
    FOR Day ← 2 TO 6
        IF Steps[Day] > Steps[Best]
            THEN
                _____(i)_____
        ENDIF
    NEXT Day
    _____(ii)_____
ENDFUNCTION

[2]

(d) State the value that the call MostActiveDay(StepCounts) would return for the data given above, and name the day of the week (Monday to Saturday) that this index represents. [2]

Question 4

Structured 7 marks

A school app stores the quiz marks for 3 students across 4 quizzes in a two-dimensional array, Marks, declared as ARRAY[1:3, 1:4], where the first index is the student number and the second index is the quiz number.

DECLARE Marks : ARRAY[1:3, 1:4] OF INTEGER
DECLARE Student : INTEGER
DECLARE Quiz : INTEGER
DECLARE RowTotal : INTEGER
DECLARE ColumnTotal : INTEGER

Marks[1,1] ← 8
Marks[1,2] ← 6
Marks[1,3] ← 9
Marks[1,4] ← 7
Marks[2,1] ← 5
Marks[2,2] ← 7
Marks[2,3] ← 6
Marks[2,4] ← 8
Marks[3,1] ← 9
Marks[3,2] ← 9
Marks[3,3] ← 8
Marks[3,4] ← 10

(a) State the value of Marks[2,3]. [1]

(b) The nested loop below calculates and outputs the total mark for each student, by adding together all four of their quiz marks.

FOR Student ← 1 TO 3
    RowTotal ← 0
    FOR Quiz ← 1 TO 4
        RowTotal ← RowTotal + Marks[Student, Quiz]
    NEXT Quiz
    OUTPUT RowTotal
NEXT Student

Trace this nested loop and state the three values that are output, in order. [3]

(c) A second version of the program swaps the order of the two loops, as shown below, to calculate a total for each quiz instead.

FOR Quiz ← 1 TO 4
    ColumnTotal ← 0
    FOR Student ← 1 TO 3
        ColumnTotal ← ColumnTotal + Marks[Student, Quiz]
    NEXT Student
    OUTPUT ColumnTotal
NEXT Quiz

State what real-world quantity each value of ColumnTotal represents, and calculate the value of the first output (for Quiz 1). [2]

(d) In the array declaration ARRAY[1:3, 1:4], state which index, the first or the second, represents the student number, and which represents the quiz number. [1]

Question 5

Structured 6 marks

A program stores the high scores from a simple game, held in the array Scores, in a text file called scores.txt, with one score written per line. Scores contains 4 values: Scores[1] ← 82, Scores[2] ← 95, Scores[3] ← 78, Scores[4] ← 90.

(a) Complete the pseudocode below, which opens the file for writing, writes all 4 values from Scores to the file, one per line, and then closes the file. Write the missing pseudocode statement for each of the lines labelled (i), (ii) and (iii).

DECLARE Index : INTEGER
_____(i)_____
FOR Index ← 1 TO 4
    _____(ii)_____
NEXT Index
_____(iii)_____

[3]

(b) The file scores.txt now contains four lines: 82, 95, 78, 90. A separate procedure reads every score back from the file and adds it to a running total, using the EOF function so that it works correctly whatever number of scores the file contains.

DECLARE FileScore : INTEGER
DECLARE RunningTotal : INTEGER
RunningTotal ← 0
OPENFILE "scores.txt" FOR READ
WHILE NOT EOF("scores.txt")
    READFILE "scores.txt", FileScore
    RunningTotal ← RunningTotal + FileScore
ENDWHILE
CLOSEFILE "scores.txt"
OUTPUT RunningTotal

Trace this code and state the value output for RunningTotal. [2]

(c) State one reason why the procedure in (b) uses WHILE NOT EOF("scores.txt") to control the loop, rather than a fixed count such as FOR Index ← 1 TO 4. [1]

Question 6

Structured 5 marks

An online clothing store uses a procedure, ShowDiscountedPrice, to work out and display the discounted price of an item, given its original price and a discount percentage.

PROCEDURE ShowDiscountedPrice(ItemPrice : REAL, DiscountPercent : INTEGER)
    DECLARE Discounted : REAL
    Discounted ← ItemPrice - (ItemPrice * DiscountPercent / 100)
    OUTPUT Discounted
ENDPROCEDURE

CALL ShowDiscountedPrice(40.00, 25)

(a) State the value that the parameter ItemPrice holds, and the value that the parameter DiscountPercent holds, during this call. [1]

(b) Trace the procedure for this call, showing your working, and state the value output. [2]

(c) A second call is written, by mistake, with the two arguments the wrong way round: CALL ShowDiscountedPrice(25, 40). State the value that would be output by this call, showing your working, and explain why it is different from the value in part (b), even though the same two numbers, 25 and 40, are used in both calls. [2]

Question 7

Multiple choice 1 mark

An online coding bootcamp uses a function, IsPassMark, to check whether a learner's score on a short quiz meets the pass mark required for that particular module.

FUNCTION IsPassMark(Score : INTEGER, PassMark : INTEGER) RETURNS BOOLEAN
    IF Score >= PassMark
        THEN
            RETURN TRUE
        ELSE
            RETURN FALSE
    ENDIF
ENDFUNCTION

DECLARE Result1 : BOOLEAN
DECLARE Result2 : BOOLEAN
Result1 ← IsPassMark(48, 50)
Result2 ← IsPassMark(72, 50) AND IsPassMark(72, 70)
OUTPUT Result1
OUTPUT Result2

What is displayed, in order, by the two OUTPUT statements above?

Question 8

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]

Question 9

Multiple choice 1 mark

A weather monitoring system stores temperature readings, in degrees Celsius, from 3 sensors over 3 days in a two-dimensional array, Readings, declared as ARRAY[1:3, 1:3], where the first index is the sensor number and the second index is the day number. The nested loop below counts how many of the 9 readings are above 25 degrees Celsius.

DECLARE Readings : ARRAY[1:3, 1:3] OF INTEGER
DECLARE Sensor : INTEGER
DECLARE Day : INTEGER
DECLARE Count : INTEGER

Readings[1,1] ← 22
Readings[1,2] ← 27
Readings[1,3] ← 19
Readings[2,1] ← 26
Readings[2,2] ← 24
Readings[2,3] ← 30
Readings[3,1] ← 18
Readings[3,2] ← 25
Readings[3,3] ← 29

Count ← 0
FOR Sensor ← 1 TO 3
    FOR Day ← 1 TO 3
        IF Readings[Sensor, Day] > 25
            THEN
                Count ← Count + 1
        ENDIF
    NEXT Day
NEXT Sensor
OUTPUT Count

What value is output for Count?

Question 10

Structured 6 marks

A small sports club stores its members' names in a text file, register.txt, one name per line, so the membership list survives between seasons. The pseudocode below reads every name from the file into a one-dimensional array, Names, declared with room for up to 10 names, and counts how many names were actually read.

DECLARE Names : ARRAY[1:10] OF STRING
DECLARE NameCount : INTEGER
DECLARE NextName : STRING

NameCount ← 0
OPENFILE "register.txt" FOR READ
WHILE NOT EOF("register.txt")
    READFILE "register.txt", NextName
    NameCount ← NameCount + 1
    Names[NameCount] ← NextName
ENDWHILE
CLOSEFILE "register.txt"
OUTPUT NameCount

register.txt currently contains exactly four lines, in this order: Amara, Beth, Chidi, Dev.

(a) State the value output for NameCount after this code runs. [1]

(b) State the value of Names[3] after this code runs. [1]

(c) State what Names[5] to Names[10] hold after this code runs, and explain why. [2]

(d) A club administrator wants to add a fifth member, Esi, to the end of register.txt without erasing the four names already stored there. State the file mode that OPENFILE should use for this, and explain why OPENFILE "register.txt" FOR WRITE would not achieve this. [2]