S
Topic 8 Structure & data · 8.12 · 8.13 · 8.14 · 8.15 · 8.16

Structure & Data Lab

Subroutines · Library Routines · Maintainability · Arrays · File Handling. The architectural elements that turn code into software students can be proud of.

📚 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

8.12 Use procedures and functions, understand parameters (up to 3 in 2026 syllabus)
8.13 Use library routines MOD, DIV, ROUND, RANDOM, LENGTH, SUBSTRING, LCASE, UCASE
8.14 Identify maintainability features: comments, meaningful identifiers, subroutines, indentation, constants
8.15 Declare 1D and 2D arrays, access with index, iterate with loops
8.16 Open, read, write and close text files; detect EOF

📖 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. Up to 3 allowed (2026 syllabus).
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 routinePre-built function provided by the language (LENGTH, ROUND, RANDOM etc.).
MODRemainder after integer division. 17 MOD 5 = 2.
DIVInteger division (discards remainder). 17 DIV 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. Cambridge indexes start at 1 by default.
Text fileA file storing characters, read/written one line at a time.
EOFEnd Of File — the marker used to stop reading a file.
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)x <- Name(args) inside an expression
KeywordPROCEDURE ... ENDPROCEDUREFUNCTION ... RETURN ... ENDFUNCTION

2. Cambridge Library Routines

RoutineWhat it doesExample
MODRemainder17 MOD 5 → 2
DIVInteger divide17 DIV 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(s)Number of chars in stringLENGTH("Cat") → 3
SUBSTRING(s,p,n)n chars starting at position p (1-based)SUBSTRING("Cambridge",1,3) → "Cam"
LCASE(s)Lowercase copy of stringLCASE("HELLO") → "hello"
UCASE(s)Uppercase copy of stringUCASE("hello") → "HELLO"

3. Maintainability Checklist (memorise for 6-mark question)

TechniqueWhy it helps future readers
Meaningful identifier namesStudentAge is obvious. x is not.
CommentsExplain WHY the code does something, not just what.
Indentation and white spaceShows structure at a glance.
ConstantsChange TaxRate in one place, not 20.
SubroutinesReusable, self-contained, easier to test.

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 (all 4 operations)

OperationSyntax
Open for readingOPENFILE "data.txt" FOR READ
Open for writing (overwrites)OPENFILE "data.txt" FOR WRITE
Open for appendingOPENFILE "data.txt" FOR APPEND
Read one lineREADFILE "data.txt", Buffer
Write one lineWRITEFILE "data.txt", Content
Close fileCLOSEFILE "data.txt"
Detect endWHILE NOT EOF("data.txt") ... ENDWHILE

✏️ Worked Examples

Example 1: Function with 3 parameters (2026 syllabus)

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

// Main program
DECLARE V : INTEGER
V <- AreaOfBox(3, 4, 5)   // V is now 60
OUTPUT V

Why it matters: The 2026 syllabus explicitly allows up to 3 parameters. Earlier syllabuses limited to 2. Learn this well — the s25 examiner report withdrew a question that required 3 parameters, so Cambridge has now updated the syllabus.

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 a file until EOF

DECLARE Line : STRING
OPENFILE "notes.txt" FOR READ
WHILE NOT EOF("notes.txt")
    READFILE "notes.txt", Line
    OUTPUT Line
ENDWHILE
CLOSEFILE "notes.txt"

Pattern: Every file read follows this same 4-step shape: OPEN → WHILE NOT EOF → READ → CLOSE. Learn it as one unit.

⚠️ Common Misconceptions

❌ Calling a function without using its return value

A function returns a value — you must capture it: x <- MyFunc(). Writing MyFunc() 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 quotient, MOD gives the remainder. 17 DIV 5 = 3, 17 MOD 5 = 2. Use MOD to test divisibility: IF x MOD 2 = 0 checks if x is even.

Cited: recurring across 2023–2025 papers

❌ 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: comments, meaningful names, subroutines, indentation, constants.

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.
3-parameter functions: The 2026 syllabus allows up to 3 parameters. Old past-paper answers may only use 2 — check the year.
CALL command: When calling a procedure with an argument, Cambridge expects CALL ProcName(x). Just writing ProcName(x) may cost marks.
Array declaration: Always DECLARE Name : ARRAY[lower:upper] OF TYPE. Colon separator, bounds in brackets. Cambridge indexes start at 1 by default.
Maintainability list: Memorise 5 techniques (comments, meaningful names, indentation, constants, subroutines). Give a good description for each — 6 marks are common.
File read pattern: Always OPEN → WHILE NOT EOF → READ → CLOSE. Never READ without checking EOF first.
ROUND has TWO arguments: Cambridge ROUND takes (value, decimal_places). ROUND(3.567, 1) → 3.6. Many students forget the second argument.
MOD for divisibility: IF Number MOD 2 = 0 is the standard "is even" test. Learn this pattern.

🧪 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. What's the maximum number of parameters allowed in the 2026 syllabus?
3 parameters. Previously 2. Announced in the s25 examiner report.
3. Give one 2D array declaration.
DECLARE Grid : ARRAY[1:5, 1:4] OF INTEGER — 5 rows, 4 columns of integers.
4. Name 3 maintainability techniques.
Any 3 of: comments · meaningful identifier names · indentation and white space · constants for magic numbers · use of subroutines.
5. What's the file-read loop pattern?
WHILE NOT EOF("file.txt") ... READFILE ... ENDWHILE — then CLOSEFILE after.
6. What does 17 MOD 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

Topic 8.12–8.16 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: These are Paper 2's hardest programming questions. The 15-mark question almost always involves at least an array and a subroutine, sometimes files too.

Discussion: Which of the 5 sub-topics 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)
    OUTPUT "Hi ", Name
ENDPROCEDURE

CALL Greet("Sam")

FUNCTION

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

FUNCTION Double(x)
  RETURNS INTEGER
    RETURN x * 2
ENDFUNCTION

y <- Double(7)  // y 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 Cambridge pattern you can step through, poke at, and break.

Click a mode above to begin.

🔧 Refactor Lab · Turn an ugly program maintainable

Click each improvement to apply it. Watch the code transform. Watch the maintainability score climb.

Current Code
0/5 Maintainability techniques applied
Available Improvements

📘 Cambridge Syntax Reference

Copy these skeletons. Fill in the blanks. These are the shapes examiners expect to see.

// Procedure with parameter PROCEDURE Name(Param : TYPE) // body ENDPROCEDURE // Called with: CALL Name(value)
// Function with parameters + return FUNCTION Name(a : INTEGER, b : INTEGER) RETURNS INTEGER RETURN a + b ENDFUNCTION // Called with: Total <- Name(3, 5)
// 1D array declare + use DECLARE Scores : ARRAY[1:10] OF INTEGER Scores[1] <- 87 // Iterate: FOR i <- 1 TO 10 OUTPUT Scores[i] NEXT i
// 2D array declare + use DECLARE Grid : ARRAY[1:5, 1:4] OF STRING Grid[2, 3] <- "X" // Iterate (both dims!): FOR r <- 1 TO 5 FOR c <- 1 TO 4 OUTPUT Grid[r, c] NEXT c NEXT r
// File: read every line OPENFILE "data.txt" FOR READ WHILE NOT EOF("data.txt") READFILE "data.txt", Line OUTPUT Line ENDWHILE CLOSEFILE "data.txt"
// File: append a line OPENFILE "log.txt" FOR APPEND WRITEFILE "log.txt", "New 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. The 5 accepted techniques: comments · meaningful names · indentation · constants · subroutines.

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"

❌ Reading a file without checking EOF first

If you READFILE past the last line, the program crashes. Always WHILE NOT EOF("file.txt") before READFILE.

Cited: Recurring in Cambridge programming questions

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

Cited: Multiple examiner reports 2023–2025

❌ Confusing arguments and parameters

Parameters are declared in the subroutine header. Arguments are the actual values passed in the call. FUNCTION F(x) has parameter x; F(5) passes 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

10 rapid-fire questions on subroutines, arrays, and library routines. Timer starts on your first answer.

Press Start to begin the sprint.

✎ Adaptive Practice

🧪 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

Every question below is Cambridge-style with a paper citation. Type your answer, submit for keyword auto-marking, then reveal the model answer.

🔄 Cambridge Trap Review

10 traps drawn from the last 3 years of examiner reports. Memorise these.

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 Q10(b) — verbatim

2. CALL keyword omitted for procedures with parameters

Cambridge mark schemes list CALL as an explicit expected keyword. Some sessions, "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 = comments · meaningful names · indentation · constants · subroutines. Learn these 5 exactly.

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

6. ROUND with one argument

Cambridge ROUND = ROUND(value, dp). Missing the dp argument = missing marks.

Cited: Multiple sessions 2023–2025

7. Function called without capturing the return value

If a function returns something, use it: Answer <- Calc(x). Writing just Calc(x) 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

Cambridge marks off for x, y, data, Array, temp. Use StudentAge, TotalPrice, HighestScore.

Cited: recurring — meaningful identifiers rule

🧠 Memory Triggers

PvsF: Procedure = does; Function = returns.
C-M-I-C-S: Comments · Meaningful names · Indentation · Constants · Subroutines. The 5 maintainability techniques.
OWCR: Open → While-not-EOF → Read → Close. The file-read shape.
Two dims, two loops: A 2D array always needs a nested FOR.
ROUND takes two: ROUND(value, dp).
3P from 2026: Functions can take up to 3 parameters.

🏆 Skills Mastery

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

📋 Revision Checklist

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 ✓