S
Topic 8 Programming · Page 8.12–8.16

Structure & Data Lab

Subroutines · Library Routines · Maintainability · Arrays · File Handling. The building blocks that turn short scripts into real, well-organised programs.

📚 Topic Overview

Every real program uses these five ideas together. Subroutines package tasks. Library routines save you from re-inventing common operations. Maintainability makes code readable to future you. Arrays store many values under one name. File handling makes data survive when the program closes. This is where you stop writing tiny scripts and start writing software.

🎯 Learning Objectives

Subroutines — write and call procedures and functions with up to three parameters; know local and global scope
Library routines — use MOD, DIV, ROUND and RANDOM
Maintainability — explain meaningful identifiers, comments, and procedures/functions (indentation and constants are also good practice)
Arrays — declare 1D and 2D arrays, access elements with an index, and use loops to process them
Files — open, read, write and close text files

📖 Key Terminology

TermMeaning
ProcedureA named block of code that performs a task but does not return a value.
FunctionA named block of code that returns a single value using RETURNS.
ParameterA named input to a subroutine, listed in brackets with its data type. Up to three can be used.
ArgumentThe actual value passed to a parameter when the subroutine is called.
Global scopeA variable declared outside any subroutine — accessible everywhere.
Local scopeA variable declared inside a subroutine — only exists in that subroutine.
Library routineA ready-made routine provided by the language: MOD, DIV, ROUND, RANDOM.
MODRemainder after integer division. MOD(17, 5) = 2.
DIVInteger division (discards remainder). DIV(17, 5) = 3.
1D arrayA list of values under one name, accessed by one index. Scores[3]
2D arrayA table of values with rows and columns. Grid[Row, Col]
IndexThe position number of an array element. The declaration shows the first index (usually 1).
Text fileA file storing characters, read/written one line at a time.
File modeHow a file is opened: FOR READ (to read from it) or FOR WRITE (to write to it, replacing its contents).
Meaningful identifierA name that describes the value: StudentAge, not x.

🧠 Core Theory

1. Procedure vs Function

FeaturePROCEDUREFUNCTION
PurposePerform a taskCalculate and RETURN a value
ReturnsNothingExactly one value (RETURNS TYPE)
Called withCALL Name(args)Result ← Name(args) — used inside an expression
KeywordPROCEDURE ... ENDPROCEDUREFUNCTION ... RETURN ... ENDFUNCTION

2. Library Routines

RoutineWhat it doesExample
MOD(a, b)RemainderMOD(17, 5) → 2
DIV(a, b)Integer divideDIV(17, 5) → 3
ROUND(x,d)Rounds x to d decimal placesROUND(3.567, 1) → 3.6
RANDOM()Random real between 0 and 1RANDOM() → 0.4271...

LENGTH, SUBSTRING, LCASE and UCASE are string handling functions — they are covered in the Decisions & Patterns lab.

3. Maintainability

Syllabus featureWhy it helps future readers
Meaningful identifiersStudentAge is obvious. X is not.
CommentsExplain what a section of code does, and why.
Procedures and functionsEach task is in a named, self-contained block that can be reused and tested on its own.

Also good practice: indentation and white space (show the structure), and named constants (change a value such as TaxRate in one place).

4. Array Declaration & Access

TypeDeclareAccess
1D arrayDECLARE Scores : ARRAY[1:10] OF INTEGERScores[3] ← 87
2D arrayDECLARE Grid : ARRAY[1:5, 1:4] OF STRINGGrid[2, 3] ← "X"

5. File Handling

OperationSyntax
Open for readingOPENFILE "data.txt" FOR READ
Open for writing (replaces the contents)OPENFILE "data.txt" FOR WRITE
Read one line into a variableREADFILE "data.txt", Line
Write a variable as one lineWRITEFILE "data.txt", Line
Close fileCLOSEFILE "data.txt"

📎 Useful background (not needed for the exam)

Some textbooks and real languages also use FOR APPEND (add to the end of a file without deleting it) and EOF() (test for the end of a file, e.g. WHILE NOT EOF("data.txt")). These are not part of the syllabus pseudocode, so exam questions won't require them.

✏️ Worked Examples

Example 1: Function with three parameters

FUNCTION AreaOfBox(Length : INTEGER, Width : INTEGER, Height : INTEGER) RETURNS INTEGER
    RETURN Length * Width * Height
ENDFUNCTION

// Main program
DECLARE BoxVolume : INTEGER
BoxVolume ← AreaOfBox(3, 4, 5)   // BoxVolume is now 60
OUTPUT BoxVolume

Why it matters: Procedures and functions can have up to three parameters. Each parameter has a name and a data type, and the header ends with RETURNS and the type of the value sent back.

Example 2: Iterating a 2D array (recurring exam trap)

DECLARE Points : ARRAY[1:4, 1:3] OF INTEGER
DECLARE Total : INTEGER

Total ← 0
FOR Row ← 1 TO 4
    FOR Col ← 1 TO 3
        Total ← Total + Points[Row, Col]
    NEXT Col
NEXT Row
OUTPUT Total

Trap: Cambridge examiner reports flag candidates who "did not use both dimensions" — students often iterate one row and forget the outer loop.

Example 3: Reading from and writing to files

DECLARE Line : STRING
// read the first three lines and output them
OPENFILE "notes.txt" FOR READ
FOR Count ← 1 TO 3
    READFILE "notes.txt", Line
    OUTPUT Line
NEXT Count
CLOSEFILE "notes.txt"

// write a new line (replaces the old contents)
OPENFILE "backup.txt" FOR WRITE
WRITEFILE "backup.txt", Line
CLOSEFILE "backup.txt"

Pattern: OPENFILE (FOR READ or FOR WRITE) → READFILE or WRITEFILE → CLOSEFILE. Learn it as one unit.

⚠️ Common Misconceptions

❌ Calling a function without using its return value

A function returns a value — you must use it: Result ← MyFunc(5). Writing MyFunc(5) alone throws the value away. Procedures don't have this problem because they don't return anything.

Cited: 2025 s25 examiner report — "struggled with writing a function with a parameter"

❌ Iterating an array without an index or a loop

You cannot process all 200 members by referring to the array name alone. You need FOR i ← 1 TO 200 and access Members[i] inside. This is one of the most-cited exam errors.

Cited: 2024 w24 examiner report — "did not use an index with the array or use a loop to input all"

❌ Confusing MOD and DIV

DIV gives the whole-number part, MOD gives the remainder: DIV(17, 5) = 3, MOD(17, 5) = 2. Use MOD to test divisibility: IF MOD(Number, 2) = 0 checks if Number is even.

Common exam mistake

❌ Naming maintenance techniques as "validation" or "loops"

Maintainability is about making code READABLE, not correct. Validation checks input; loops repeat code. Neither improves maintainability. Say: meaningful identifiers, comments, and procedures/functions (indentation and constants also help).

Cited: 2023 s23 examiner report — "Many candidates suggested verification, validation and the use of loops"

❌ Forgetting CLOSEFILE

Every OPENFILE needs a matching CLOSEFILE. Files left open can lose data or block other programs. Cambridge mark schemes explicitly reward the CLOSEFILE line.

Cited: 2024 s24 examiner report — file handling questions

❌ Using only one dimension of a 2D array

A 2D array needs BOTH indexes: Grid[Row, Col]. Students often iterate just rows and forget columns, or use Grid[Row] which isn't valid Cambridge syntax.

Cited: 2023 w23 examiner report — "failed to use both dimensions"

🎯 Cambridge Exam Focus

Function with parameter: If the question mentions "function", you MUST use RETURNS TYPE and RETURN. Otherwise you'll lose the function marks and get procedure marks at best.
Parameters: A procedure or function can have up to three parameters, each with a data type: (Length : INTEGER, Width : INTEGER, Height : INTEGER).
CALL command: Procedures are called with CALL ProcName(Value). The 2025 w25 examiner report noted few candidates used CALL correctly.
Array declaration: Always DECLARE Name : ARRAY[lower:upper] OF TYPE. Colon separator, bounds in brackets. The lower bound is the first index (usually 1).
Maintainability: Lead with the syllabus features — meaningful identifiers, comments, procedures and functions — and say how each helps. Indentation and constants are extra good practice.
File pattern: OPENFILE … FOR READ or FOR WRITE → READFILE / WRITEFILE → CLOSEFILE. Never forget CLOSEFILE.
ROUND has TWO arguments: ROUND(Value, Places). ROUND(3.567, 1) → 3.6. Don't forget the second argument.
MOD for divisibility: IF MOD(Number, 2) = 0 is the standard "is even" test.

🧪 Quick Knowledge Check

1. What's the difference between a procedure and a function?
A procedure performs a task and returns nothing. A function performs a task and returns exactly one value using RETURNS.
2. How many parameters can a procedure or function have?
Up to three. Each one has a name and a data type.
3. Give one 2D array declaration.
DECLARE Grid : ARRAY[1:5, 1:4] OF INTEGER — 5 rows, 4 columns of integers.
4. Name the three maintainability features in the syllabus.
Meaningful identifiers, comments, and procedures/functions. (Indentation and named constants are also good practice.)
5. What are the steps to read a line from a text file?
OPENFILE "file.txt" FOR READ → READFILE "file.txt", Line → CLOSEFILE "file.txt".
6. What does MOD(17, 5) evaluate to?
2 — MOD returns the remainder after integer division.

✅ Ready for Activities

You know the syntax for procedures and functions, arrays (1D and 2D), library routines, and file handling. You can spot maintainability techniques. Head to Activities to try them hands-on.

📖 Getting Started

This lab is where a program stops being a script and becomes software. You'll build the tools that let programs grow: named blocks of code that you can call anywhere (subroutines), pre-built utilities (library routines), habits that keep code readable (maintainability), containers for lots of data (arrays), and permanent storage (files).

Context: The longer programming question at the end of Paper 2 often uses arrays and subroutines, and can include files.

Discussion: Which of the 5 ideas do you already feel confident with? Which one worries you? Book Notes covers the theory; this Learn tab makes each one hands-on.

🔀 Contrast: Procedure vs Function

These two words describe subroutines, but they behave differently. Getting the choice right is worth marks.

PROCEDURE

Does a task. No return value. Called with CALL.

PROCEDURE Greet(Name : STRING)
    OUTPUT "Hi ", Name
ENDPROCEDURE

CALL Greet("Sam")

FUNCTION

Calculates a value. Returns it via RETURN. Called inside an expression.

FUNCTION Double(Number : INTEGER) RETURNS INTEGER
    RETURN Number * 2
ENDFUNCTION

Answer ← Double(7)  // Answer is 14

WHICH?

Ask: does the caller need a result? If yes → function. If it just needs the task done → procedure.

Test: "Print welcome" = procedure. "Calculate area" = function.

🏛️ Structure Studio · 4 hands-on modes

Pick a mode. Each shows a working pattern you can step through and explore.

Click a mode above to begin.

🔧 Refactor Lab · Turn an ugly program maintainable

Click each improvement to apply it. The first three are the syllabus maintainability features; the last two are extra good practice.

Current Code
0/5 Improvements applied
Available Improvements

📘 Cambridge Syntax Reference

Copy these skeletons and fill in the blanks. They follow the syllabus pseudocode style.

// Procedure with parameter PROCEDURE Name(Param : TYPE) // body ENDPROCEDURE // Called with: CALL Name(value)
// Function with parameters + return FUNCTION Name(Num1 : INTEGER, Num2 : INTEGER) RETURNS INTEGER RETURN Num1 + Num2 ENDFUNCTION // Called with: Total ← Name(3, 5)
// 1D array declare + use DECLARE Scores : ARRAY[1:10] OF INTEGER Scores[1] ← 87 // Iterate: FOR Index ← 1 TO 10 OUTPUT Scores[Index] NEXT Index
// 2D array declare + use DECLARE Grid : ARRAY[1:5, 1:4] OF STRING Grid[2, 3] ← "X" // Iterate (both dims!): FOR Row ← 1 TO 5 FOR Col ← 1 TO 4 OUTPUT Grid[Row, Col] NEXT Col NEXT Row
// File: read 5 lines OPENFILE "data.txt" FOR READ FOR Count ← 1 TO 5 READFILE "data.txt", Line OUTPUT Line NEXT Count CLOSEFILE "data.txt"
// File: write a line (replaces contents) OPENFILE "log.txt" FOR WRITE WRITEFILE "log.txt", Entry CLOSEFILE "log.txt"

⚠️ Traps to watch for

❌ Missing RETURNS TYPE in a function declaration

Every FUNCTION must declare what type it returns — RETURNS INTEGER, RETURNS STRING, etc. Without RETURNS TYPE, the mark scheme reads it as a procedure.

Cited: 2025 s25 Q10(b) examiner report — parameter+function question

❌ Naming maintenance techniques as "validation" or "verification"

Validation is about correct input. Maintainability is about readable CODE. Give the syllabus features: meaningful identifiers · comments · procedures and functions (indentation and constants also help).

Cited: 2023 s23 examiner report — verbatim

❌ Iterating an array without using the index in the loop body

Even if you write FOR i ← 1 TO 10, if you write INPUT Scores (no [i]) you're not using the loop counter. Use INPUT Scores[i].

Cited: 2024 w24 examiner report — "did not use an index with the array"

❌ Only iterating one dimension of a 2D array

A 2D array needs a nested loop: outer for rows, inner for columns. If you only loop rows, you access Grid[r, 1] for every row — same column repeated.

Cited: 2023 w23 examiner report — "failed to use both dimensions"

❌ Opening a file in the wrong mode

OPENFILE … FOR WRITE replaces everything already in the file. To get data out of a file, open it FOR READ and use READFILE.

Common exam mistake

❌ Forgetting to declare LOCAL variables inside subroutines

Variables declared inside a PROCEDURE or FUNCTION are LOCAL — they only exist during that call. Trying to OUTPUT them from main after the call fails.

Cited: 2024 m24 examiner report — scope questions

❌ Using ROUND with only one argument

Cambridge ROUND takes TWO arguments: value and decimal places. ROUND(3.567) is incomplete. Write ROUND(3.567, 1) → 3.6.

Common exam mistake

❌ Confusing arguments and parameters

Parameters are declared in the subroutine header. Arguments are the actual values passed in the call. In FUNCTION Square(Number : INTEGER) RETURNS INTEGER, Number is the parameter; Square(5) passes the argument 5.

Cited: 2025 s25 examiner report — terminology accuracy

🎮 Activities · 5 drills · each with stretch questions

Each drill mixes easy, medium, and exam-level questions. Watch for the EXAM tag — those are the stretch questions.

🧩 Drill 1 · Subroutine Sorter

A pseudocode snippet is shown. Say whether it's a procedure or a function — and why.

🔢 Drill 2 · Array Index Predictor

An array is shown with a value at some index. Predict what the code will output.

🎲 Drill 3 · Library Routine Value

A library routine is called. What does it return?

📁 Drill 4 · File Operation Order

Given a file task, pick the correct sequence of file operations.

⚡ Drill 5 · 60-second Sprint

Rapid questions on subroutines, arrays, library routines and files. Answer as many as you can in 60 seconds.

Press Start to begin the sprint.

✎ Practice questions

🧪 Exam Mode ON — options hidden. Recall the answer, then reveal.
Filter:

Questions are weighted — weaker skills come up more often, and there are no immediate repeats.

📋 Exam-style Questions

Written questions in the Paper 2 style. Type your answer, mark it, then compare it with the model answer.

🔄 Cambridge Trap Review

10 traps to memorise.

1. Function without a parameter when one is required

Cambridge often asks for a function that takes a value in. Writing FUNCTION F() RETURNS INTEGER when the question says "takes x as a parameter" costs the parameter mark AND breaks the calling code.

Cited: 2025 s25 examiner report — function with a parameter

2. CALL keyword omitted for procedures with parameters

Procedures are called with CALL. In one recent session, "few were able to complete the task using the CALL command."

Cited: 2025 w25 Q2(b)(i) — verbatim

3. Array processed without an index or a loop

If the array has 200 elements, you need FOR i ← 1 TO 200. Referring to Members alone processes nothing.

Cited: 2024 w24 — "did not use an index with the array or use a loop"

4. Only one dimension of a 2D array used

2D arrays need both indexes and nested loops. Iterating Grid[r] without Grid[r, c] misses the second dimension.

Cited: 2023 w23 — "failed to use both dimensions"

5. Maintainability described as "validation" or "using loops"

Wrong. Maintainability = meaningful identifiers · comments · procedures and functions (plus indentation and constants as good practice).

Cited: 2023 s23 — "Many candidates suggested verification, validation and the use of loops"

6. ROUND with one argument

ROUND takes two arguments: ROUND(Value, Places). Leaving out the number of places is incomplete.

Common exam mistake

7. Function called without capturing the return value

If a function returns something, use it: Answer ← Calc(Value). Writing just Calc(Value) throws the value away and often means the code is a procedure by mistake.

Cited: 2025 s25 — function-writing question

8. Forgetting CLOSEFILE

Every OPENFILE needs a CLOSEFILE. Mark schemes reward this explicitly.

Cited: 2024 s24 — file question

9. Local variable referenced outside its subroutine

Variables declared inside PROCEDURE/FUNCTION are LOCAL. They don't exist in main after the call. Return the value if you need it in main.

Cited: 2024 m24 — scope question

10. Meaningful identifier missing

Examiners expect meaningful identifiers — avoid x, y, data, Array, temp. Use StudentAge, TotalPrice, HighestScore.

Cited: recurring — meaningful identifiers rule

🧠 Memory Triggers

PvsF: Procedure = does; Function = returns.
M-C-P: Meaningful identifiers · Comments · Procedures and functions. The syllabus maintainability features.
O-R-C: Open → Read (or Write) → Close. The file shape.
Two dims, two loops: A 2D array always needs a nested FOR.
ROUND takes two: ROUND(value, dp).
Up to 3: A procedure or function can take up to three parameters.

🏆 Skills Mastery

Green = ≥70% accuracy over 3+ attempts. Yellow = 30–69%. Grey = untried. Tap a badge to override.

📋 Revision Checklist

✅ Topic 8 complete

That's the end of Topic 8: Programming. Next, Topic 9 covers databases: tables, records, fields, primary keys and SQL.

Mistake Log

Mistakes

Your recent mistakes

Progress

Progress

Practice

0Attempts
–Accuracy

Exam

0Attempts
–Avg match
Bookmarks

Bookmarked Exam Questions

My Notes

My Notes

Add note

Your notes

Knowledge Vault 2.0

Knowledge Vault

Add entry

Category
Confidence
Title
Info

Entries

Saved ✓