Programming (GCSE & IGCSE Computer Science): Revision Notes and Worksheets

GCSE and IGCSE Computer Science programming: variables, data types, operators, IF and CASE, loops, strings, arrays, files, procedures, functions, records.

Diagram comparing three loop types: a count-controlled FOR loop that repeats a set number of times, a pre-condition WHILE loop that checks its condition before the body, and a post-condition loop that runs the body first and checks its condition after.

Every program, from a phone game to a booking system, is built from the same small set of tools: variables, decisions, loops, arrays and sub programs. This guide covers GCSE and IGCSE programming: variables and constants, data types, operators, selection, the three kinds of loop, nesting, strings, 1D and 2D arrays, files, procedures, functions, parameters, local and global variables, random numbers, records and maintainable code. Each part has a worked example and a worksheet for your exam board.

Cambridge IGCSE 0478 students: you need every part except M27, and only the points marked IGCSE or Both boards. Part M27 (records) is on the OCR J277 specification only. OCR J277 students: you need all 22 parts, and only the points marked GCSE or Both boards. The part numbers skip M2, M4, M13, M15, M17 and M20.

What does programming cover for OCR and Cambridge?

Both boards test programming on their second paper. OCR J277 covers it in 2.2 (Programming fundamentals), with nesting in 2.1.2 and maintainable code in 2.3.1. Cambridge IGCSE 0478 covers it in topic 8 (Programming). The ideas are almost the same; what changes is how the code is written. The table below is based on the OCR J277 specification (version 3.1) and the Cambridge IGCSE 0478 syllabus for 2026-2028, as checked in November 2026. Totalling and counting are in Standard algorithms revision notes (L7), SQL is in Databases and SQL revision notes, and input validation is in Robust programs revision notes.

Part

Topic

OCR J277

Cambridge 0478

M1

Variables, constants, input and output (both boards)

2.2.1

8.1.1, 8.1.3, 8.1.4(a)

M3

Data types and casting (both boards; casting GCSE only)

2.2.2

8.1.2

M5

Arithmetic operators, MOD and DIV (both boards)

2.2.1

8.1.4(f)

M6

Comparison operators (both boards)

2.2.1

8.1.4(f)

M7

Boolean operators AND, OR, NOT (both boards)

2.2.1

8.1.4(f)

M8

Selection: IF and ELSE (both boards)

2.2.1

8.1.4(b)

M9

Selection: CASE and switch (both boards)

2.2.1

8.1.4(b)

M10

Count-controlled loops, FOR (both boards)

2.2.1

8.1.4(c)

M11

Condition-controlled loops, WHILE (both boards)

2.2.1

8.1.4(c)

M12

Post-condition loops and choosing a loop (both boards)

2.2.1

8.1.4(c)

M14

Nested selection and loops (both boards)

2.1.2

8.1.5

M16

String handling (both boards)

2.2.3

8.1.4(e)

M18

One-dimensional arrays (both boards)

2.2.3

8.2.1-8.2.3

M19

Two-dimensional arrays (both boards)

2.2.3

8.2.1-8.2.3

M21

File handling (both boards)

2.2.3

8.3.1, 8.3.2

M22

Procedures (both boards)

2.2.3

8.1.6(a), (b)

M23

Functions and return values (both boards)

2.2.3

8.1.6(a), (b)

M24

Parameters and arguments (both boards)

2.2.3

8.1.6(a), (b)

M25

Local and global variables (both boards)

2.2.3

8.1.6(c)

M26

Library routines and random numbers (both boards; library routines IGCSE only)

2.2.3

8.1.7

M27

Records (GCSE only)

2.2.3

not on syllabus

M28

Maintainable code (both boards)

2.3.1

8.1.8

GCSE only: OCR shows code in its Exam Reference Language (lower-case keywords, = to assign, arrays and strings counted from 0). You can answer in Exam Reference Language or a high-level language you have studied. IGCSE only: Cambridge shows code in Cambridge pseudocode (upper-case keywords, ← to assign, arrays and strings usually counted from 1), and written code answers must be in that pseudocode; under the 2026-2028 syllabus, only the final 15-mark question also accepts Python, Visual Basic or Java. Both notations are shown in every part below.

Concept

OCR Exam Reference Language

Cambridge pseudocode

Assign

total = 0

Total ← 0

Equal, not equal

== and !=

= and <>

Input and output

x = input("Prompt"), print(x)

INPUT X, OUTPUT X

Multi-way IF

elseif

nested IF inside ELSE

Loops

for ... next, while ... endwhile, do ... until

FOR ... NEXT, WHILE ... DO ... ENDWHILE, REPEAT ... UNTIL

First array index

0

usually 1 (stated in the declaration)

Call a procedure

showMenu()

CALL ShowMenu

M1: What are variables, constants, inputs and outputs?

Both boards. A variable is a named memory location that stores a value that can change while the program runs. A constant is a named value that cannot change while the program runs. Constants make code easier to read, and if the value ever needs updating, it is changed in one place.

Assignment stores a value in a variable: the expression on the right is worked out first, then the result is stored in the variable on the left. A variable holds one value at a time, so a new value overwrites the old one. Input is data entered by the user and stored in a variable; output is data shown to the user. Sequence means statements run one after another, in the order they are written.

OCR Exam Reference Language (GCSE only):

const maxSeats = 52
name = input("Enter your name")
booked = 0
print("Hello " + name)
const maxSeats = 52
name = input("Enter your name")
booked = 0
print("Hello " + name)
const maxSeats = 52
name = input("Enter your name")
booked = 0
print("Hello " + name)

Cambridge pseudocode (IGCSE only):

CONSTANT MaxSeats ← 52
DECLARE Name : STRING
DECLARE Booked : INTEGER
OUTPUT "Enter your name"
INPUT Name
Booked ← 0
OUTPUT "Hello ", Name
CONSTANT MaxSeats ← 52
DECLARE Name : STRING
DECLARE Booked : INTEGER
OUTPUT "Enter your name"
INPUT Name
Booked ← 0
OUTPUT "Hello ", Name
CONSTANT MaxSeats ← 52
DECLARE Name : STRING
DECLARE Booked : INTEGER
OUTPUT "Enter your name"
INPUT Name
Booked ← 0
OUTPUT "Hello ", Name
  • GCSE only: OCR assigns with = and needs no declaration. Constants use const. The prompt goes inside input(), and print() outputs.

  • IGCSE only: Cambridge assigns with ← and declares each variable with its data type (DECLARE). A constant's value must be a literal, such as 52 or "N/A", never a variable or an expression. INPUT takes no prompt, so output the message first. OUTPUT separates values with commas.

Worked example: follow the values (both boards)

A shop's stock program runs three assignments in sequence. In OCR they start stock = 40; in Cambridge, Stock ← 40.

  • Step 1: stock = 40. The variable now holds 40.

  • Step 2: stock = stock - 15. The right side is worked out first: 40 - 15 = 25, and 25 overwrites 40.

  • Step 3: stock = stock + 30. 25 + 30 = 55. Outputting stock now shows 55; the old values 40 and 25 are gone.

Practise M1: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M3: What are data types, and what is casting?

Both boards. A data type decides what values can be stored and what can be done with them. You need five:

  • Integer: a whole number, such as 52 or -3.

  • Real: a number that can have a fractional part, such as 3.75 or -0.5.

  • Boolean: one of two values, TRUE or FALSE.

  • Character: a single character, such as 'M' or '@'.

  • String: a sequence of characters, such as "07700 900123". A string can be empty.

Choose the type from the data. A phone number is a string: it keeps its leading 0, can hold spaces, and is never used in a calculation.

GCSE only: casting temporarily changes the data type of a value, where this is useful. For example, int("3") turns the string "3" into the integer 3 so it can be used in a calculation, and str(345) turns a number into a string so it can be joined to text. OCR's casting functions are str(), int(), float(), real() and bool().

IGCSE only: Cambridge declares types with the keywords INTEGER, REAL, CHAR, STRING and BOOLEAN, for example DECLARE InStock : BOOLEAN. A REAL value is written with a digit on both sides of the point, such as 4.0 or 0.5, a CHAR in single quotes ('M') and a STRING in double quotes. Casting is not on the 0478 syllabus.

Worked example: choose the types for a café order (both boards)

  • Step 1: the number of drinks, 4, is an integer; the price of one drink, 3.75, is a real.

  • Step 2: the table letter 'B' is a character; the note "no ice" is a string; whether the order is paid is a Boolean.

  • Step 3 (GCSE only): qty = int(input("How many drinks?")). The user types 4; casting turns the text "4" into the integer 4, so total = qty * 3.75 gives 15.0. print("Total: " + str(total)) casts it back to a string to join it to the text.

Practise M3: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M5: How do the arithmetic operators, MOD and DIV work?

Both boards. The arithmetic operators are + (add), - (subtract), * (multiply), / (divide: 10 / 4 = 2.5) and ^ (exponent, "to the power of": 2 ^ 3 = 8). Two more work with whole numbers:

  • MOD (modulo) gives the remainder after whole-number division: 17 MOD 5 = 2.

  • DIV (quotient) gives the whole-number result of a division, with the fractional part thrown away: 17 DIV 5 = 3.

A number MOD 2 is 0 when the number is even. DIV and MOD together split a quantity into units, such as minutes into hours and minutes. Multiplication and division are done before addition and subtraction; use brackets to make the order clear.

  • GCSE only: OCR writes MOD and DIV between the values: 17 MOD 5, 17 DIV 5.

  • IGCSE only: Cambridge writes them as functions: MOD(17, 5) returns 2 and DIV(17, 5) returns 3. Cambridge's arithmetic operators are limited to + - / * ^ MOD DIV.

Worked example: 200 minutes in hours and minutes (both boards)

  • Step 1: hours = 200 DIV 60 = 3 (60 goes into 200 three whole times). Cambridge: DIV(200, 60).

  • Step 2: minutes = 200 MOD 60 = 20 (3 × 60 = 180, and 200 - 180 = 20). Cambridge: MOD(200, 60).

  • Step 3: check: 3 × 60 + 20 = 200, so 200 minutes is 3 hours 20 minutes. And watch the order: 4 + 6 * 2 = 16, but (4 + 6) * 2 = 20.

Practise M5: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M6: What are comparison operators?

Both boards. A comparison operator compares two values and always gives a Boolean result, TRUE or FALSE. Comparisons are the conditions in IF statements and condition-controlled loops. They can compare numbers, characters or strings, for example checking an input against a password.

Meaning

OCR (GCSE)

Cambridge (IGCSE)

Equal to

==

=

Not equal to

!=

<>

Less than, less than or equal to

< and <=

< and <=

Greater than, greater than or equal to

> and >=

> and >=

Boundaries matter: >= 18 includes 18, but > 18 does not. In code answers, write the operator, not English ("is greater than").

  • GCSE only: in OCR, a single = is assignment, so equality is ==: if answer == "Yes" then.

  • IGCSE only: Cambridge assigns with ←, so equality is a single =: UNTIL Password = "Secret". Cambridge calls these relational operators.

Worked example: free delivery for orders of 50 or more (both boards)

  • Step 1: "50 or more" includes 50, so the condition is total >= 50 (Cambridge: Total >= 50).

  • Step 2: test the boundary: an order of exactly 50 gives TRUE with >=, but FALSE with > 50. That is the most common error.

  • Step 3: test either side: 49.99 gives FALSE and 50.01 gives TRUE.

Practise M6: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M7: How do AND, OR and NOT work in code?

Both boards. Boolean operators combine or reverse conditions. The keywords are the same on both boards.

  • AND: TRUE only when both conditions are TRUE.

  • OR: TRUE when at least one condition is TRUE.

  • NOT: reverses a Boolean value: NOT TRUE gives FALSE.

A range check joins two comparisons with AND: rating >= 1 AND rating <= 10. "Out of range" is the reverse, joined with OR: rating < 1 OR rating > 10. Each side needs a full comparison: rating >= 1 AND <= 10 is wrong. Use brackets to make the order clear in longer conditions. IGCSE only: Cambridge's logical operators are limited to AND, OR and NOT.

Worked example: is the rating from 1 to 10? (both boards)

  • Step 1: rating 0: 0 >= 1 is FALSE, so FALSE AND anything is FALSE. Rejected.

  • Step 2: rating 7: 7 >= 1 is TRUE and 7 <= 10 is TRUE, so the result is TRUE. Accepted.

  • Step 3: rating 11: the out-of-range test 11 < 1 OR 11 > 10 is FALSE OR TRUE, which is TRUE. NOT(rating >= 1 AND rating <= 10) gives the same result for every rating.

Practise M7: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M8: How does IF, ELSE IF and ELSE selection work?

Both boards. Selection tests a condition to decide which code runs next. An IF block runs only when its condition is TRUE, and the ELSE block runs when it is FALSE. In a multi-way choice the conditions are tested in order, and only the first TRUE branch runs, so the order of range tests matters. Indentation shows which statements belong to each branch.

OCR Exam Reference Language (GCSE only):

if weight <= 2 then
    cost = 3.50
elseif weight <= 10 then
    cost = 6.00
else
    cost = 9.80
endif
if weight <= 2 then
    cost = 3.50
elseif weight <= 10 then
    cost = 6.00
else
    cost = 9.80
endif
if weight <= 2 then
    cost = 3.50
elseif weight <= 10 then
    cost = 6.00
else
    cost = 9.80
endif

Cambridge pseudocode (IGCSE only):

IF Weight <= 2
  THEN
    Cost ← 3.50
  ELSE
    IF Weight <= 10
      THEN
        Cost ← 6.00
      ELSE
        Cost ← 9.80
    ENDIF
ENDIF
IF Weight <= 2
  THEN
    Cost ← 3.50
  ELSE
    IF Weight <= 10
      THEN
        Cost ← 6.00
      ELSE
        Cost ← 9.80
    ENDIF
ENDIF
IF Weight <= 2
  THEN
    Cost ← 3.50
  ELSE
    IF Weight <= 10
      THEN
        Cost ← 6.00
      ELSE
        Cost ← 9.80
    ENDIF
ENDIF
  • GCSE only: OCR has elseif, one word with its own then. One endif closes the whole statement.

  • IGCSE only: Cambridge has no ELSE IF: nest another IF ... ENDIF inside the ELSE (or use CASE, M9). THEN and ELSE start new lines, indented two spaces under the IF.

Worked example: parcel postage (both boards)

  • Step 1: a 1.5 kg parcel: 1.5 <= 2 is TRUE, so cost = 3.50 and no other test runs. A 2 kg parcel also costs 3.50, because <= includes 2.

  • Step 2: a 7 kg parcel: the first test is FALSE, 7 <= 10 is TRUE, so cost = 6.00. A 12 kg parcel fails both tests, so the ELSE gives 9.80.

  • Step 3: swap the tests so weight <= 10 comes first, and the 1.5 kg parcel now costs 6.00: wrong. Test the narrowest range first.

Practise M8: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M9: How do CASE and switch statements work?

Both boards. A CASE (or switch) statement selects one of several branches depending on the value of a single variable. The cases are checked in order; when one matches, its code runs and the statement is finished. The default (OCR) or OTHERWISE (Cambridge) branch comes last and runs only if no case matches. Use CASE to test one variable against fixed values; use IF for ranges and complex conditions.

OCR Exam Reference Language (GCSE only):

switch choice:
    case "A":
        print("Add an item")
    case "D":
        print("Delete an item")
    default:
        print("Invalid option")

switch choice:
    case "A":
        print("Add an item")
    case "D":
        print("Delete an item")
    default:
        print("Invalid option")

switch choice:
    case "A":
        print("Add an item")
    case "D":
        print("Delete an item")
    default:
        print("Invalid option")

Cambridge pseudocode (IGCSE only):

CASE OF Choice
  'A' : OUTPUT "Add an item"
  'D' : OUTPUT "Delete an item"
  OTHERWISE OUTPUT "Invalid option"
ENDCASE
CASE OF Choice
  'A' : OUTPUT "Add an item"
  'D' : OUTPUT "Delete an item"
  OTHERWISE OUTPUT "Invalid option"
ENDCASE
CASE OF Choice
  'A' : OUTPUT "Add an item"
  'D' : OUTPUT "Delete an item"
  OTHERWISE OUTPUT "Invalid option"
ENDCASE
  • GCSE only: OCR puts a colon after the variable and after each case value; default: catches everything else; endswitch closes it.

  • IGCSE only: Cambridge writes CASE OF, then each value, a colon and one statement, indented two spaces. OTHERWISE has no colon and, if used, must be the last case.

Worked example: a menu (both boards)

  • Step 1: the user enters D. The first case, A, does not match; D does, so the output is Delete an item, and no more cases are checked.

  • Step 2: the user enters X. No case matches, so the default / OTHERWISE branch outputs Invalid option.

  • Step 3: the user enters a lower-case a. 'a' is a different value from 'A', so this also outputs Invalid option.

Practise M9: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M10: How does a count-controlled (FOR) loop work?

Both boards. Iteration means repeating code. A count-controlled loop repeats a set number of times, so use it when you know the number of repeats before the loop starts. The loop variable takes every value from the start to the end, inclusive: 0 to 9 and 1 to 10 both run 10 times. A step sets how much the loop variable changes each time; a negative step counts down. The loop variable can be used inside the loop, for example in a calculation or as an array index.

OCR Exam Reference Language (GCSE only):

total = 0
for i = 1 to 5
    total = total + i * 2
next i
print(total)
total = 0
for i = 1 to 5
    total = total + i * 2
next i
print(total)
total = 0
for i = 1 to 5
    total = total + i * 2
next i
print(total)

Cambridge pseudocode (IGCSE only):

Total ← 0
FOR Index ← 1 TO 5
    Total ← Total + Index * 2
NEXT Index
OUTPUT Total
Total ← 0
FOR Index ← 1 TO 5
    Total ← Total + Index * 2
NEXT Index
OUTPUT Total
Total ← 0
FOR Index ← 1 TO 5
    Total ← Total + Index * 2
NEXT Index
OUTPUT Total
  • GCSE only: OCR: for i = 10 to 0 step -1 ... next i.

  • IGCSE only: Cambridge: FOR Count ← 10 TO 0 STEP -1 ... NEXT Count. The loop variable is an INTEGER.

Worked example: trace the loop (both boards)

  • Step 1: i = 1: total = 0 + 2 = 2. i = 2: total = 2 + 4 = 6.

  • Step 2: i = 3: total = 12. i = 4: total = 20. i = 5: total = 30. The loop ran 5 times and outputs 30.

  • Step 3: count without tracing: a loop from 3 to 15 with step 4 gives 3, 7, 11, 15, so it runs 4 times.

Practise M10: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M11: How does a condition-controlled (WHILE) loop work?

Both boards. A WHILE loop repeats while a condition is TRUE, so the number of repeats does not need to be known in advance. The condition is checked before each pass, so the body may run zero times. The loop ends when the condition becomes FALSE. The body must change something the condition tests, or the loop never ends (an infinite loop), and the variables in the condition need a value before the loop starts.

OCR Exam Reference Language (GCSE only):

water = 1000
hours = 0
while water >= 300
    water = water - 250
    hours = hours + 1
endwhile
print(hours)
water = 1000
hours = 0
while water >= 300
    water = water - 250
    hours = hours + 1
endwhile
print(hours)
water = 1000
hours = 0
while water >= 300
    water = water - 250
    hours = hours + 1
endwhile
print(hours)

Cambridge pseudocode (IGCSE only):

Water ← 1000
Hours ← 0
WHILE Water >= 300 DO
    Water ← Water - 250
    Hours ← Hours + 1
ENDWHILE
OUTPUT Hours
Water ← 1000
Hours ← 0
WHILE Water >= 300 DO
    Water ← Water - 250
    Hours ← Hours + 1
ENDWHILE
OUTPUT Hours
Water ← 1000
Hours ← 0
WHILE Water >= 300 DO
    Water ← Water - 250
    Hours ← Hours + 1
ENDWHILE
OUTPUT Hours
  • GCSE only: OCR calls it a condition-controlled loop: while ... endwhile.

  • IGCSE only: Cambridge calls it a pre-condition loop and puts DO after the condition: WHILE ... DO ... ENDWHILE.

Worked example: draining a tank (both boards)

  • Step 1: 1000 >= 300 is TRUE: water = 750, hours = 1. 750 >= 300: water = 500, hours = 2.

  • Step 2: 500 >= 300: water = 250, hours = 3. Now 250 >= 300 is FALSE, so the loop ends and the output is 3.

  • Step 3: if water started at 200, the first check is FALSE, the body runs zero times, and the output is 0.

Practise M11: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M12: What is a post-condition loop, and which loop should you choose?

Both boards. In a post-condition loop the condition is checked after the body, so the body always runs at least once. It repeats until the condition becomes TRUE: the opposite sense to WHILE, which runs while its condition is TRUE. A typical use is input validation: ask, check, and ask again until the input is acceptable.

OCR Exam Reference Language (GCSE only):

do
    guests = int(input("Number of guests (1 to 8)"))
until guests >= 1 AND guests <= 8
do
    guests = int(input("Number of guests (1 to 8)"))
until guests >= 1 AND guests <= 8
do
    guests = int(input("Number of guests (1 to 8)"))
until guests >= 1 AND guests <= 8

Cambridge pseudocode (IGCSE only):

REPEAT
    OUTPUT "Number of guests (1 to 8)"
    INPUT Guests
UNTIL Guests >= 1 AND Guests <= 8
REPEAT
    OUTPUT "Number of guests (1 to 8)"
    INPUT Guests
UNTIL Guests >= 1 AND Guests <= 8
REPEAT
    OUTPUT "Number of guests (1 to 8)"
    INPUT Guests
UNTIL Guests >= 1 AND Guests <= 8

Choosing a loop:

  • Count-controlled (FOR): the number of repeats is known before the loop starts.

  • WHILE (pre-condition): the body may need to run zero times.

  • Post-condition: the body must run at least once.

GCSE only: OCR writes do ... until, and calls both while and do-until condition-controlled loops. IGCSE only: Cambridge writes REPEAT ... UNTIL, and names three loop types: count-controlled, pre-condition and post-condition.

Diagram comparing three loop types: a count-controlled FOR loop that repeats a set number of times, a pre-condition WHILE loop that checks its condition before the body, and a post-condition loop that runs the body first and checks its condition after.

Worked example: validate the number of guests (both boards)

  • Step 1: the user enters 0. The condition 0 >= 1 AND 0 <= 8 is FALSE, so the loop repeats. The user enters 12: also FALSE, so it repeats again.

  • Step 2: the user enters 5. The condition is TRUE, so the loop stops after asking 3 times, with guests = 5.

  • Step 3: to rewrite it as a WHILE loop, ask once before the loop and reverse the condition: keep asking while guests < 1 OR guests > 8 (Cambridge: WHILE Guests < 1 OR Guests > 8 DO).

Practise M12: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M14: How do nested IF statements and nested loops work?

Both boards. Nesting puts one construct inside another: an IF inside an IF, a loop inside a loop, or an IF inside a loop. In a nested IF, the inner condition is tested only when the outer branch containing it is taken. In nested loops, the inner loop runs all its passes for each single pass of the outer loop, so nested FOR loops run the inner body outer count × inner count times. Each nested structure needs its own end keyword, and indentation shows which block is which.

OCR Exam Reference Language (GCSE only):

for row = 1 to 3
    for col = 1 to 4
        print(row * col)
    next col
next row
for row = 1 to 3
    for col = 1 to 4
        print(row * col)
    next col
next row
for row = 1 to 3
    for col = 1 to 4
        print(row * col)
    next col
next row

Cambridge pseudocode (IGCSE only):

FOR Row ← 1 TO 3
    FOR Col ← 1 TO 4
        OUTPUT Row * Col
    NEXT Col
NEXT Row
FOR Row ← 1 TO 3
    FOR Col ← 1 TO 4
        OUTPUT Row * Col
    NEXT Col
NEXT Row
FOR Row ← 1 TO 3
    FOR Col ← 1 TO 4
        OUTPUT Row * Col
    NEXT Col
NEXT Row

GCSE only: OCR lists nesting under 2.1.2: use nesting for selection and iteration in algorithms you write or refine. IGCSE only: Cambridge 8.1.5 includes nested selection and iteration, and you will not have to write more than three levels of nesting.

Worked example: a hotel discount (both boards)

The outer IF checks whether the guest is a member. Only for members, an inner IF checks the nights: 3 or more nights gives a 20% discount, fewer gives 10%. Non-members get no discount.

  • Step 1: a member staying 4 nights: outer TRUE, inner TRUE, discount = 20. A member staying 2 nights: outer TRUE, inner FALSE, discount = 10.

  • Step 2: a non-member staying 5 nights: outer FALSE, so the inner IF is never tested, and discount = 0.

  • Step 3: in the nested loops above, the inner body runs 3 × 4 = 12 times, and the last value output is 3 × 4 = 12.

Practise M14: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M16: How do you handle strings?

Both boards. String handling means working with text: finding its length (the number of characters, including spaces), taking a substring (part of the string, given by a start position and a number of characters), and converting to upper case or lower case, for example to compare inputs whatever case they were typed in. Always check whether the first character is position 0 or position 1 before counting.

Diagram of the string "Lighthouse" in ten boxes, numbered 0 to 9 for OCR and 1 to 10 for Cambridge, showing that OCR substring(5, 5) and Cambridge SUBSTRING("Lighthouse", 6, 5) both give "house".
  • GCSE only: OCR uses dot methods and counts from 0: s.length, s.upper, s.lower, s.substring(start, count), s.left(n) and s.right(n). Concatenation joins strings with +, and taking part of a string is called slicing. ASC("A") gives 65 and CHR(97) gives "a".

  • IGCSE only: Cambridge uses functions: LENGTH(S), UCASE(S), LCASE(S) and SUBSTRING(S, Start, Length). The first character can be position 0 or 1, but is generally 1; questions say which. Cambridge pseudocode has no concatenation operator: OUTPUT joins values with commas.

Worked example: "Lighthouse" (both boards)

  • Step 1: the length is 10 (OCR s.length, Cambridge LENGTH(S)).

  • Step 2: the last five letters, "house", start at OCR index 5 but Cambridge position 6: s.substring(5, 5) and SUBSTRING("Lighthouse", 6, 5) both give "house". In upper case it is "LIGHTHOUSE".

  • Step 3 (GCSE only): a product code from the first three letters and a size: part = s.left(3) gives "Lig", then code = part.upper + "XL" gives "LIGXL".

Practise M16: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M18: What is a one-dimensional array?

Both boards. An array is a fixed-length data structure that stores elements of the same data type under one identifier. Each element is reached by its index in square brackets. The index can be a variable, so a FOR loop can visit every element in turn to write values in or read them out. Arrays store many related values without a separate variable for each. An array is a static structure: its size is set when it is declared and does not change.

OCR Exam Reference Language (GCSE only):

array temps = [12, 15, 9, 18, 11]
total = 0
for i = 0 to 4
    total = total + temps[i]
next i
print(total / 5)
array temps = [12, 15, 9, 18, 11]
total = 0
for i = 0 to 4
    total = total + temps[i]
next i
print(total / 5)
array temps = [12, 15, 9, 18, 11]
total = 0
for i = 0 to 4
    total = total + temps[i]
next i
print(total / 5)

Cambridge pseudocode (IGCSE only):

DECLARE Temps : ARRAY[1:5] OF INTEGER
DECLARE Index : INTEGER
DECLARE Total : INTEGER
// values stored one at a time, e.g. Temps[1] ← 12
Total ← 0
FOR Index ← 1 TO 5
    Total ← Total + Temps[Index]
NEXT Index
OUTPUT Total / 5
DECLARE Temps : ARRAY[1:5] OF INTEGER
DECLARE Index : INTEGER
DECLARE Total : INTEGER
// values stored one at a time, e.g. Temps[1] ← 12
Total ← 0
FOR Index ← 1 TO 5
    Total ← Total + Temps[Index]
NEXT Index
OUTPUT Total / 5
DECLARE Temps : ARRAY[1:5] OF INTEGER
DECLARE Index : INTEGER
DECLARE Total : INTEGER
// values stored one at a time, e.g. Temps[1] ← 12
Total ← 0
FOR Index ← 1 TO 5
    Total ← Total + Temps[Index]
NEXT Index
OUTPUT Total / 5
  • GCSE only: OCR arrays are 0-indexed: array colours[5] has indexes 0 to 4. An array can be declared and filled in one line, as above.

  • IGCSE only: Cambridge declares the lower and upper bound and the type: ARRAY[1:30] OF STRING. The first index can be 0 or 1, but is generally 1.

Worked example: total, mean and highest (both boards)

  • Step 1: total = 12 + 15 + 9 + 18 + 11 = 65, so the mean is 65 / 5 = 13.

  • Step 2: to find the highest, start with the first element, 12, and compare each one: 15 is higher, 9 is not, 18 is higher, 11 is not. The highest is 18.

  • Step 3: 18 is the fourth element: OCR index 3 (temps[3]), Cambridge index 4 (Temps[4]).

Practise M18: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M19: How do two-dimensional arrays work?

Both boards. A 2D array stores elements in rows and columns, and each element is reached with two indexes. Exam examples use [row, column], but follow the order the question gives. Every element has the same data type, and the size is fixed when the array is declared. To visit every element, use nested loops: the outer loop over the rows, the inner loop over the columns. One row or one column needs only a single loop.

Diagram of a 2D array of sales with 3 rows (stalls) and 4 columns (days), showing OCR indexes from 0 and Cambridge indexes from 1, with OCR sales[1,2] and Cambridge Sales[2,3] pointing to the same element, 4, and row totals 28, 20 and 24.

OCR Exam Reference Language (GCSE only):

total = 0
for row = 0 to 2
    for col = 0 to 3
        total = total + sales[row, col]
    next col
next row
print(total)
total = 0
for row = 0 to 2
    for col = 0 to 3
        total = total + sales[row, col]
    next col
next row
print(total)
total = 0
for row = 0 to 2
    for col = 0 to 3
        total = total + sales[row, col]
    next col
next row
print(total)

Cambridge pseudocode (IGCSE only):

DECLARE Sales : ARRAY[1:3, 1:4] OF INTEGER
Total ← 0
FOR Row ← 1 TO 3
    FOR Col ← 1 TO 4
        Total ← Total + Sales[Row, Col]
    NEXT Col
NEXT Row
OUTPUT Total
DECLARE Sales : ARRAY[1:3, 1:4] OF INTEGER
Total ← 0
FOR Row ← 1 TO 3
    FOR Col ← 1 TO 4
        Total ← Total + Sales[Row, Col]
    NEXT Col
NEXT Row
OUTPUT Total
DECLARE Sales : ARRAY[1:3, 1:4] OF INTEGER
Total ← 0
FOR Row ← 1 TO 3
    FOR Col ← 1 TO 4
        Total ← Total + Sales[Row, Col]
    NEXT Col
NEXT Row
OUTPUT Total
  • GCSE only: OCR declares array sales[3,4] (rows 0 to 2, columns 0 to 3). OCR also uses 2D arrays to emulate a database table: each row is a record and each column a field.

  • IGCSE only: Cambridge declares both sets of bounds, ARRAY[1:3, 1:4] OF INTEGER, and assigns one element at a time, for example Sales[2, 3] ← 4.

Worked example: a market's sales (both boards)

The rows are three stalls and the columns four days: 5, 8, 6, 9 / 7, 3, 4, 6 / 2, 9, 8, 5.

  • Step 1: the second stall's third day is OCR sales[1, 2] and Cambridge Sales[2, 3]: both are 4.

  • Step 2: one loop along the second row gives that stall's total: 7 + 3 + 4 + 6 = 20. One loop down the second column gives that day's total: 8 + 3 + 9 = 20.

  • Step 3: the nested loops above add all 12 elements: 28 + 20 + 24 = 72.

Practise M19: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M21: How do you open, read, write and close a file?

Both boards. Data stored in a file stays after the program closes, so it can be loaded again next time. A program must open a file before using it, read (copy the next line or item from the file into a variable) and/or write (store a value or line of text in the file), then close it once it is no longer needed. A loop can process every line of a file.

OCR Exam Reference Language (GCSE only):

visits = open("visits.txt")
count = 0
while NOT visits.endOfFile()
    print(visits.readLine())
    count = count + 1
endwhile
visits.close()
print(count)
visits = open("visits.txt")
count = 0
while NOT visits.endOfFile()
    print(visits.readLine())
    count = count + 1
endwhile
visits.close()
print(count)
visits = open("visits.txt")
count = 0
while NOT visits.endOfFile()
    print(visits.readLine())
    count = count + 1
endwhile
visits.close()
print(count)

Cambridge pseudocode (IGCSE only):

DECLARE LineOfText : STRING
DECLARE Count : INTEGER
OPENFILE "Visits.txt" FOR READ
FOR Count ← 1 TO 3
    READFILE "Visits.txt", LineOfText
    OUTPUT LineOfText
NEXT Count
CLOSEFILE "Visits.txt"
DECLARE LineOfText : STRING
DECLARE Count : INTEGER
OPENFILE "Visits.txt" FOR READ
FOR Count ← 1 TO 3
    READFILE "Visits.txt", LineOfText
    OUTPUT LineOfText
NEXT Count
CLOSEFILE "Visits.txt"
DECLARE LineOfText : STRING
DECLARE Count : INTEGER
OPENFILE "Visits.txt" FOR READ
FOR Count ← 1 TO 3
    READFILE "Visits.txt", LineOfText
    OUTPUT LineOfText
NEXT Count
CLOSEFILE "Visits.txt"
  • GCSE only: OCR stores the open file in a variable. readLine() returns the next line, and writeLine("...") adds a line to the end of the file. endOfFile() is TRUE after the last line. newFile("x.txt") creates a new file, which is then opened with open().

  • IGCSE only: Cambridge opens a file in one mode at a time: FOR READ or FOR WRITE. Opening FOR WRITE creates a new file, and any existing data is lost. WRITEFILE "Visits.txt", NewVisit writes the value of a variable. Cambridge 8.3.1 also asks for the purpose of storing data in a file, as described above.

Worked example: a visitor log with 3 lines (both boards)

  • Step 1: both programs above open the file, read and output each of the 3 lines, then close it. The OCR version also counts them: it outputs 3.

  • Step 2 (GCSE only): OCR opens the file and runs visits.writeLine("Fri 14:05 Unit 4"). The line goes on the end, so the file now has 4 lines.

  • Step 3 (IGCSE only): Cambridge opens the file FOR WRITE and writes one line. The file is created afresh, so it now has 1 line; the 3 old lines are lost.

Practise M21: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M22: What is a procedure?

Both boards. A sub program is a named block of code that does a specific task and runs when it is called. A procedure is a sub program that carries out a task but does not return a value. When a procedure is called, its code runs, then control returns to the line after the call. It is defined once and can be called as many times as needed, so the same code is not repeated. Sub programs make code structured: easier to read, test, debug and maintain, and reusable. A procedure can have parameters or none (M24).

OCR Exam Reference Language (GCSE only):

procedure showBanner()
    print("==========")
    print("Car park open")
    print("==========")
endprocedure

showBanner()
procedure showBanner()
    print("==========")
    print("Car park open")
    print("==========")
endprocedure

showBanner()
procedure showBanner()
    print("==========")
    print("Car park open")
    print("==========")
endprocedure

showBanner()

Cambridge pseudocode (IGCSE only):

PROCEDURE ShowBanner
    OUTPUT "=========="
    OUTPUT "Car park open"
    OUTPUT "=========="
ENDPROCEDURE

CALL ShowBanner
PROCEDURE ShowBanner
    OUTPUT "=========="
    OUTPUT "Car park open"
    OUTPUT "=========="
ENDPROCEDURE

CALL ShowBanner
PROCEDURE ShowBanner
    OUTPUT "=========="
    OUTPUT "Car park open"
    OUTPUT "=========="
ENDPROCEDURE

CALL ShowBanner
  • GCSE only: OCR calls a procedure with its name and brackets, no keyword: showBanner().

  • IGCSE only: Cambridge must use CALL: CALL ShowBanner. A procedure with no parameters has no brackets.

Worked example: call it four times (both boards)

  • Step 1: the main program calls the procedure. Its 3 output lines run, then control goes back to the line after the call.

  • Step 2: a sign display calls it 4 times, so 4 × 3 = 12 lines are output.

  • Step 3: without the procedure, those 3 lines would be written out 4 times. To change the message, the procedure is edited in one place.

Practise M22: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M23: What is a function, and what does it return?

Both boards. A function is a sub program that returns a single value to the point where it was called. RETURN sends the value back. A function call is used inside an expression: assigned to a variable, output, or compared. Store the returned value in a variable if it is needed later. Both procedures and functions carry out a task; only a function returns a value.

OCR Exam Reference Language (GCSE only):

function roomArea(length, width)
    area = length * width
    return area
endfunction

floorSize = roomArea(4.5, 3.2)
function roomArea(length, width)
    area = length * width
    return area
endfunction

floorSize = roomArea(4.5, 3.2)
function roomArea(length, width)
    area = length * width
    return area
endfunction

floorSize = roomArea(4.5, 3.2)

Cambridge pseudocode (IGCSE only):

FUNCTION RoomArea(Length : REAL, Width : REAL) RETURNS REAL
    RETURN Length * Width
ENDFUNCTION

FloorSize ← RoomArea(4.5, 3.2)
FUNCTION RoomArea(Length : REAL, Width : REAL) RETURNS REAL
    RETURN Length * Width
ENDFUNCTION

FloorSize ← RoomArea(4.5, 3.2)
FUNCTION RoomArea(Length : REAL, Width : REAL) RETURNS REAL
    RETURN Length * Width
ENDFUNCTION

FloorSize ← RoomArea(4.5, 3.2)
  • GCSE only: OCR writes function ... return ... endfunction, and calls it within an expression: print(roomArea(4.5, 3.2)).

  • IGCSE only: the Cambridge header must state the RETURNS data type and the type of each parameter. Never use CALL with a function.

Worked example: two rooms (both boards)

  • Step 1: roomArea(4.5, 3.2) works out 4.5 × 3.2 and returns 14.4, which is stored in floorSize.

  • Step 2: roomArea(3.0, 2.0) returns 6.0.

  • Step 3: calls can sit inside one expression: roomArea(4.5, 3.2) + roomArea(3.0, 2.0) = 14.4 + 6.0 = 20.4.

Practise M23: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M24: What is the difference between a parameter and an argument?

Both boards. A parameter is a variable named in a sub program's definition that receives a value when the sub program is called. An argument is the actual value passed in the call. Arguments match parameters by position: the same number, in the same order, of a suitable data type. Inside the sub program a parameter is used like a variable. Parameters let one sub program work on different data each time it is called.

OCR Exam Reference Language (GCSE only):

procedure greetGuest(guestName, room)
    print("Welcome " + guestName + ", room " + str(room))
endprocedure

greetGuest("Ms Adeyemi", 214)
procedure greetGuest(guestName, room)
    print("Welcome " + guestName + ", room " + str(room))
endprocedure

greetGuest("Ms Adeyemi", 214)
procedure greetGuest(guestName, room)
    print("Welcome " + guestName + ", room " + str(room))
endprocedure

greetGuest("Ms Adeyemi", 214)

Cambridge pseudocode (IGCSE only):

PROCEDURE GreetGuest(GuestName : STRING, Room : INTEGER)
    OUTPUT "Welcome ", GuestName, ", room ", Room
ENDPROCEDURE

CALL GreetGuest("Ms Adeyemi", 214)
PROCEDURE GreetGuest(GuestName : STRING, Room : INTEGER)
    OUTPUT "Welcome ", GuestName, ", room ", Room
ENDPROCEDURE

CALL GreetGuest("Ms Adeyemi", 214)
PROCEDURE GreetGuest(GuestName : STRING, Room : INTEGER)
    OUTPUT "Welcome ", GuestName, ", room ", Room
ENDPROCEDURE

CALL GreetGuest("Ms Adeyemi", 214)
  • GCSE only: OCR parameters have no data types. Arrays can be passed into, and returned from, functions and procedures.

  • IGCSE only: every Cambridge parameter is given a data type, and the arguments must match those types. Procedures and functions have up to three parameters.

Worked example: match by position (both boards)

  • Step 1: in the definition, guestName and room are the parameters. In the call, "Ms Adeyemi" and 214 are the arguments.

  • Step 2: the first argument goes to the first parameter, so guestName = "Ms Adeyemi" and room = 214. The output is Welcome Ms Adeyemi, room 214.

  • Step 3: swap the arguments, (214, "Ms Adeyemi"), and the values land in the wrong parameters. In Cambridge this is a type mismatch: 214 is not a STRING.

Practise M24: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M25: What are local and global variables?

Both boards. The scope of a variable is the part of the program where it can be used. A local variable is declared inside a sub program: it can be used only there, and exists only while the sub program runs. A global variable is declared in the main program and can be used anywhere in the program. Parameters are local to their sub program.

  • Local variables: each sub program is self-contained, the same name can be reused in different sub programs, and other code cannot change them by accident.

  • Global variables: handy for a value needed everywhere, but any part of the program can change them, which makes errors harder to find.

OCR Exam Reference Language (GCSE only):

global feeRate = 0.1

procedure showPrice(price)
    withFee = price + price * feeRate
    print(withFee)
endprocedure

showPrice(50)
global feeRate = 0.1

procedure showPrice(price)
    withFee = price + price * feeRate
    print(withFee)
endprocedure

showPrice(50)
global feeRate = 0.1

procedure showPrice(price)
    withFee = price + price * feeRate
    print(withFee)
endprocedure

showPrice(50)

Cambridge pseudocode (IGCSE only):

DECLARE FeeRate : REAL
FeeRate ← 0.1

PROCEDURE ShowPrice(Price : REAL)
    DECLARE WithFee : REAL
    WithFee ← Price + Price * FeeRate
    OUTPUT WithFee
ENDPROCEDURE

CALL ShowPrice(50.0)
DECLARE FeeRate : REAL
FeeRate ← 0.1

PROCEDURE ShowPrice(Price : REAL)
    DECLARE WithFee : REAL
    WithFee ← Price + Price * FeeRate
    OUTPUT WithFee
ENDPROCEDURE

CALL ShowPrice(50.0)
DECLARE FeeRate : REAL
FeeRate ← 0.1

PROCEDURE ShowPrice(Price : REAL)
    DECLARE WithFee : REAL
    WithFee ← Price + Price * FeeRate
    OUTPUT WithFee
ENDPROCEDURE

CALL ShowPrice(50.0)
  • GCSE only: OCR's global keyword makes a variable global. OCR also asks for local and global constants used with sub programs.

  • IGCSE only: Cambridge pseudocode has no global keyword: a variable declared in the main program is global, and one declared inside a procedure or function is local.

Worked example: which variables are which? (both boards)

  • Step 1: feeRate is global: the procedure can use it although it was declared outside.

  • Step 2: price (a parameter) and withFee are local to showPrice. The call outputs 50 + 50 × 0.1 = 55.

  • Step 3: a print(withFee) in the main program, after the call, would cause an error: withFee no longer exists once the procedure ends.

Practise M25: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M26: What are library routines, and how do you make random numbers?

Both boards. Programs can generate random numbers, for example for dice, games or picking a random item. The random number is generated in a range, stored in a variable and then used in the program.

GCSE only: OCR names random number generation only. roll = random(1, 6) gives a random integer from 1 to 6 inclusive, and random(-1.0, 10.0) gives a random real number from -1.0 to 10.0.

IGCSE only: a library routine is pre-written, tested code supplied with the language and called by name. It saves time, is reliable because it is already tested, and the programmer does not need to know how it works. Cambridge 8.1.7 names four:

  • MOD and DIV: MOD(17, 5) returns 2 and DIV(17, 5) returns 3 (see M5).

  • ROUND(Value, Places): rounds to that many decimal places: ROUND(7.456, 2) returns 7.46.

  • RANDOM(): returns a random number between 0 and 1 inclusive, so it must be scaled to the range you need.

Worked example: a dice roll (both boards)

  • Step 1 (GCSE only): roll = random(1, 6) gives a whole number from 1 to 6 in one step.

  • Step 2 (IGCSE only): Roll ← ROUND(RANDOM() * 5, 0) + 1. RANDOM() * 5 gives 0 to 5; ROUND(..., 0) makes it a whole number, 0 to 5; adding 1 gives 1 to 6.

  • Step 3 (IGCSE only): ROUND(RANDOM() * 6, 0) is a common mistake: it gives 0 to 6, seven possible values.

Practise M26: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

M27: What is a record?

GCSE only. A record is a data structure that groups related fields about one item, such as one book in a library. A field is one item of data within a record, with its own name and data type. Unlike an array, a record's fields can hold different data types. You reach a single field by naming both the record and the field. A collection of records with the same fields stores many items, like the rows of a table.

OCR's Exam Reference Language has no record keyword, so this example uses record.field, as many languages do:

book.bookID = "B0412"
book.title = "Tide Tables"
book.pages = 320
book.price = 8.99
book.onLoan = False
print(book.title)
book.bookID = "B0412"
book.title = "Tide Tables"
book.pages = 320
book.price = 8.99
book.onLoan = False
print(book.title)
book.bookID = "B0412"
book.title = "Tide Tables"
book.pages = 320
book.price = 8.99
book.onLoan = False
print(book.title)

IGCSE only: records as a programming data structure are not on Cambridge 0478. The nearest Cambridge content is a record as a row of a database table (see Databases and SQL revision notes).

Worked example: design a book record (GCSE only)

  • Step 1: choose a data type for each field: bookID "B0412" string; title string; pages 320 integer; price 8.99 real; onLoan Boolean.

  • Step 2: book.pages gives 320. The book is borrowed: book.onLoan = True changes one field and leaves the others alone.

  • Step 3: an array could not hold this record, because an array stores only one data type. A 2D array can emulate a table of records if every value is stored as the same type, such as strings.

Practise M27: OCR questions · OCR mark scheme

M28: How do you write maintainable code?

Both boards. Maintainable code is easy for other programmers to read, understand, correct and update. Three features are on both boards:

  • Meaningful identifiers: names that describe what each variable, constant, array or sub program holds or does.

  • Comments: explain what the code does and why. The translator ignores them. Both boards start a comment with //.

  • Sub programs: procedures and functions split code into named, reusable parts that can be tested separately.

GCSE only: OCR 2.3.1 also lists indentation (it shows which statements belong inside each selection, loop or sub program) and naming conventions; OCR examples use camelCase, such as userID. IGCSE only: Cambridge 8.1.8 asks for meaningful identifiers for variables, constants, arrays, procedures and functions; Cambridge pseudocode uses PascalCase, such as RunningTotal.

Worked example: make this code maintainable (both boards)

Before (OCR):

a = int(input("?"))
b = 0
for c = 1 to a
b = b + c
next c
print(b)
a = int(input("?"))
b = 0
for c = 1 to a
b = b + c
next c
print(b)
a = int(input("?"))
b = 0
for c = 1 to a
b = b + c
next c
print(b)

After (OCR):

// Adds up the whole numbers from 1 to a chosen limit
function sumUpTo(limit)
    runningTotal = 0
    for number = 1 to limit
        runningTotal = runningTotal + number
    next number
    return runningTotal
endfunction

upperLimit = int(input("Enter the upper limit"))
print(sumUpTo(upperLimit))
// Adds up the whole numbers from 1 to a chosen limit
function sumUpTo(limit)
    runningTotal = 0
    for number = 1 to limit
        runningTotal = runningTotal + number
    next number
    return runningTotal
endfunction

upperLimit = int(input("Enter the upper limit"))
print(sumUpTo(upperLimit))
// Adds up the whole numbers from 1 to a chosen limit
function sumUpTo(limit)
    runningTotal = 0
    for number = 1 to limit
        runningTotal = runningTotal + number
    next number
    return runningTotal
endfunction

upperLimit = int(input("Enter the upper limit"))
print(sumUpTo(upperLimit))

After (Cambridge):

// Adds up the whole numbers from 1 to a chosen limit
FUNCTION SumUpTo(Limit : INTEGER) RETURNS INTEGER
    DECLARE RunningTotal : INTEGER
    DECLARE Number : INTEGER
    RunningTotal ← 0
    FOR Number ← 1 TO Limit
        RunningTotal ← RunningTotal + Number
    NEXT Number
    RETURN RunningTotal
ENDFUNCTION

DECLARE UpperLimit : INTEGER
OUTPUT "Enter the upper limit"
INPUT UpperLimit
OUTPUT SumUpTo(UpperLimit)
// Adds up the whole numbers from 1 to a chosen limit
FUNCTION SumUpTo(Limit : INTEGER) RETURNS INTEGER
    DECLARE RunningTotal : INTEGER
    DECLARE Number : INTEGER
    RunningTotal ← 0
    FOR Number ← 1 TO Limit
        RunningTotal ← RunningTotal + Number
    NEXT Number
    RETURN RunningTotal
ENDFUNCTION

DECLARE UpperLimit : INTEGER
OUTPUT "Enter the upper limit"
INPUT UpperLimit
OUTPUT SumUpTo(UpperLimit)
// Adds up the whole numbers from 1 to a chosen limit
FUNCTION SumUpTo(Limit : INTEGER) RETURNS INTEGER
    DECLARE RunningTotal : INTEGER
    DECLARE Number : INTEGER
    RunningTotal ← 0
    FOR Number ← 1 TO Limit
        RunningTotal ← RunningTotal + Number
    NEXT Number
    RETURN RunningTotal
ENDFUNCTION

DECLARE UpperLimit : INTEGER
OUTPUT "Enter the upper limit"
INPUT UpperLimit
OUTPUT SumUpTo(UpperLimit)
  • Step 1 (both boards): rename a, b and c to upperLimit, runningTotal and number, so each name says what it holds.

  • Step 2 (both boards): add a comment and move the calculation into a function that can be tested on its own. Both versions still output 10 when the input is 4 (1 + 2 + 3 + 4).

  • Step 3 (GCSE only): indent the loop body so it is clear which line repeats.

Practise M28: OCR questions · OCR mark scheme · Cambridge questions · Cambridge mark scheme

Common exam mistakes in programming

  • Mixing up assignment and comparison: (GCSE) OCR compares with ==, not =; (IGCSE) Cambridge assigns with ← and compares with =.

  • Leaving the variable out of the second half of a condition: age >= 18 AND <= 65. Each side needs a full comparison.

  • Using > when the rule says "or more". >= includes the boundary value.

  • Testing ranges in the wrong order in an IF chain, so a value takes the first branch that happens to be TRUE.

  • Writing the same condition for WHILE and UNTIL. WHILE runs while its condition is TRUE; a post-condition loop stops when its condition becomes TRUE.

  • Validating with a single IF, which allows only one re-entry. Use a loop.

  • Counting from the wrong index: (GCSE) OCR arrays and strings start at 0, so array temps[5] has indexes 0 to 4; (IGCSE) Cambridge generally starts at 1.

  • Resetting a running total inside the loop instead of before it.

  • Printing a value inside a function instead of returning it. (IGCSE) Using CALL with a function, or leaving CALL off a procedure.

  • (IGCSE) Thinking ROUND(RANDOM() * 6, 0) gives 1 to 6. It gives 0 to 6.

  • (IGCSE) Opening an existing file FOR WRITE: its old data is lost. (GCSE) OCR's writeLine() adds to the end.

  • Maintainability answers that describe the code instead of saying why the feature helps another programmer.

Quick recap

  • M1: a variable can change, a constant cannot; assignment works out the right side, then overwrites the variable on the left.

  • M3: integer, real, Boolean, character, string; casting with int() and str() GCSE only; DECLARE and typed literals IGCSE only.

  • M5: + - * / ^; MOD is the remainder, DIV the whole-number quotient: 17 MOD 5 = 2, 17 DIV 5 = 3.

  • M6: comparisons give TRUE or FALSE; OCR == and !=, Cambridge = and <>; >= includes the boundary.

  • M7: AND needs both, OR needs at least one, NOT reverses; each side needs a full comparison.

  • M8: only the first TRUE branch runs; OCR has elseif, Cambridge nests IF inside ELSE.

  • M9: CASE tests one variable against fixed values; default / OTHERWISE comes last.

  • M10: FOR repeats a known number of times, start to end inclusive; step can be negative.

  • M11: WHILE checks first, so it can run zero times; the body must change the condition.

  • M12: a post-condition loop runs at least once and stops when its condition is TRUE; ideal for validation.

  • M14: inner loops run fully for each outer pass (3 × 4 = 12); Cambridge writes at most three levels.

  • M16: length, substring, upper, lower; OCR counts from 0 and joins with +, Cambridge generally counts from 1.

  • M18: an array is fixed length, one data type, one identifier; loop over the indexes.

  • M19: 2D arrays use [row, column] and nested loops; OCR uses them to emulate database tables.

  • M21: open, read or write, close; OCR writeLine adds to the end; Cambridge FOR WRITE replaces the file.

  • M22: a procedure does a task and returns no value; Cambridge calls it with CALL.

  • M23: a function returns one value and is called inside an expression; Cambridge states RETURNS and never uses CALL.

  • M24: parameters are in the definition, arguments in the call, matched by position; Cambridge types them (up to three).

  • M25: local variables live inside a sub program; global variables can be used anywhere, but anything can change them.

  • M26: random numbers both boards; OCR random(1, 6); library routines MOD, DIV, ROUND, RANDOM IGCSE only.

  • M27: (GCSE only) a record groups fields of different types about one item.

  • M28: meaningful names, comments and sub programs; indentation is named by OCR.

Download the whole module

Frequently asked questions

Which parts of programming are on the Cambridge IGCSE 0478 syllabus?

Every part except M27, records. Variables, data types, operators, selection, loops, nesting, strings, arrays, files, procedures, functions, parameters, local and global variables, random numbers and maintainable code are on both OCR J277 and Cambridge 0478. Casting and records are on OCR J277 only; library routines (MOD, DIV, ROUND, RANDOM) are named on Cambridge 0478 only.

What is the difference between a variable and a constant?

Both are named values used by a program. A variable's value can change while the program runs; a constant's value cannot. Constants make code easier to read and to update, because the value is changed in one place.

What is the difference between MOD and DIV?

MOD gives the remainder after whole-number division, and DIV gives the whole-number result with the fractional part discarded. For example, 17 MOD 5 is 2 and 17 DIV 5 is 3.

What is the difference between a WHILE loop and a REPEAT UNTIL loop?

A WHILE loop checks its condition before the body, so the body can run zero times, and it repeats while the condition is true. A REPEAT UNTIL loop (do until in OCR) checks its condition after the body, so the body always runs at least once, and it repeats until the condition becomes true.

What is the difference between a procedure and a function?

Both are named sub programs that carry out a task when they are called. A function returns a value to the point where it was called, so it is used inside an expression; a procedure does not return a value.

What is the difference between a local and a global variable?

A local variable is declared inside a sub program and can only be used there, while that sub program runs. A global variable is declared in the main program and can be used anywhere in the program.

Previous module: Standard algorithms revision notes. Also see Algorithm design revision notes for pseudocode, flowcharts and trace tables.

More help: browse the GCSE Computer Science revision hub.