Skip to main content

Programming: Loops, Subroutines, Arrays and File Handling O Level Computer Science lesson

The tools of every program, in Cambridge pseudocode with Python beside it: variables and data types, input and output, selection and loops, strings and operators, procedures and functions, library routines, arrays and files.

In short: Every program, however large, is built from three structures: sequence, selection and iteration.

Updated
Scroll to begin ↓
Variables and a constant: named boxes in memoryScore : INTEGER15Score ← Score + 5changed 10 into 15PlayerName : STRING"Sam"INPUT PlayerNamestores what is typedCONSTANT MaxLives3locked: set once,never changed by the programThe name (identifier) labels the box; the value is what is inside it right now.
Each variable is a labelled box. Assignment replaces what is in the box; a constant’s box is locked.
🔍 In detailThe five basic data typesPart 2 of 22
🔍 In detailInput and outputPart 3 of 22
The three building blocks of every programSequenceSelectionIteration: WHILEIteration: REPEATone step after anotherchoose one pathtest first: may run 0 timestest last: runs at least onceINPUT PriceCost ← Price * 2OUTPUT CostAge >= 18?YesNoTicket ← 10Ticket ← 6Is N > 0?YesN ← N - 1NoINPUT PINPIN = 1234?NoYes
Sequence runs straight down. Selection takes one of two paths. A WHILE loop tests first; a REPEAT loop tests last.
🔍 In detailSelection with CASEPart 5 of 22
🔍 In detailIteration: FOR, WHILE and REPEATPart 6 of 22
A string is a row of characterspositionpseudocodeindexPython1C02O13M24P35U46T57E68R7SUBSTRING("COMPUTER", 4, 3) → "PUT"Python: word[3:6] → "PUT"Start at position 4 and take 3 characters. LENGTH("COMPUTER") is 8.
Positions count from 1 in pseudocode and indexes from 0 in Python. The yellow boxes are SUBSTRING("COMPUTER", 4, 3).
🔍 In detailArithmetic, relational and logical operatorsPart 8 of 22
🔍 In detailNested statementsPart 9 of 22
What happens when a subroutine is calledMain program1 OUTPUT "Start"2 CALL Stars(3)3 Total ← Area(4.0, 2.5)4 OUTPUT TotalPROCEDURE Stars(Count)output Count starsENDPROCEDUREFUNCTION Area(L, W)RETURN L * WENDFUNCTIONBlue: CALL passes 3 into Count, the procedure runs, then control comes back to line 3.Green: 4.0 and 2.5 go into L and W, and RETURN sends 10.0 back into line 3.
CALL jumps to the procedure and back. A function call jumps to the function, and RETURN brings a value back with it.
Global and local variablesWhole programScore (global)PROCEDURE AddBonusMessage (local)can use Score andits own MessageFUNCTION DoubleResult (local)cannot see Message;AddBonus cannot see ResultA local variable is created when its subroutine starts and lost when it ends.
Score belongs to the whole program. Message and Result each live only inside their own subroutine.
17 sweets packed into bags of 5bag 1bag 2bag 3left overDIV(17, 5) → 3how many full bagsMOD(17, 5) → 2what is left overCheck: 3 × 5 + 2 = 17. In Python: 17 // 5 is 3 and 17 % 5 is 2.
DIV counts the full bags; MOD counts what is left over.
🌍 In the real worldWriting a maintainable programPart 13 of 22
🎯 Check yourselfCheck yourself: programming conceptsPart 14 of 22
DECLARE Names : ARRAY[1:6] OF STRING[1]"Ana"[2]"Ben"[3]"Chen"[4]"Dev"[5]"Eli"[6]"Fay"indexvalueNames[4] → "Dev"With Index ← 4, Names[Index] is the same box. One name, many values, each reached by its index.
One name, six boxes. The index picks the box.
DECLARE Scores : ARRAY[1:3, 1:4] OF INTEGERsecond index: column (round)first index: row (player)12341121592021811161437191310Scores[2, 3] → 16 (row 2, column 3)
Row index first, then column index: Scores[2, 3] is 16.
✏️ Worked exampleFilling and reading arrays with loopsPart 17 of 22
🎯 Check yourselfCheck yourself: arraysPart 18 of 22
A program and its data fileProgram running in RAMHighScore ← 940Name ← "Rio"Scores.txt on storage940RioWRITEFILEREADFILElost when the program endsstill there next time
WRITEFILE copies data from a variable into the file; READFILE copies it back into a variable.
🔍 In detailOpening, reading, writing and closing a filePart 20 of 22
⚠️ Common mistakesCommon programming mistakesPart 21 of 22
🎯 Check yourselfCheck yourself: file handlingPart 22 of 22
Subtopic 1 of 3

8.1 Programming concepts

14 parts
1📘 DefinitionPart 1 / 22

Variables and constants

Variables and a constant: named boxes in memoryScore : INTEGER15Score ← Score + 5changed 10 into 15PlayerName : STRING"Sam"INPUT PlayerNamestores what is typedCONSTANT MaxLives3locked: set once,never changed by the programThe name (identifier) labels the box; the value is what is inside it right now.
Each variable is a labelled box. Assignment replaces what is in the box; a constant’s box is locked.

A program needs somewhere to keep its data while it runs. A is a named place in memory whose value can change. A is a named value that is fixed once it is set.

  • Declare a variable by giving its (its name) and its data type: DECLARE Score : INTEGER.
  • Assign it a value with the arrow, read as "becomes": Score ← 0, then Score ← Score + 5.
  • Declare a constant with its value: CONSTANT MaxLives ← 3. Trying to change it later is an error.

Pseudocode

DECLARE Score : INTEGER
DECLARE PlayerName : STRING
CONSTANT MaxLives ← 3

Score ← 10
Score ← Score + 5
OUTPUT "Lives: ", MaxLives

Python

# Python has no DECLARE: a variable is
# created the first time it is assigned.
MAX_LIVES = 3   # capitals by custom mean "constant"

score = 10
score = score + 5
print("Lives:", MAX_LIVES)

Why use a constant instead of typing 3 everywhere? If the game later allows 5 lives, you change one line, and every part of the program that uses MaxLives changes with it. Nobody has to hunt for every 3, or wonder which 3s are lives and which are something else.

Ada Lovelace. In 1843 she published a method for Charles Babbage’s Analytical Engine to calculate a sequence of numbers. Her notes include a table of named variables changing step by step, very like a trace table, and it is often called the first published computer program.Photo: Alfred Edward Chalon, Public domain, Wikimedia Commons
True or false?
Variables and constants. True or false?
Score ← Score + 1 adds one to the value already in Score.
A constant can be given a new value halfway through the program.
Total Marks is a valid identifier in Cambridge pseudocode.
2🔍 In detailPart 2 / 22

The five basic data types

Every variable has a . It tells the computer how much memory to use and what can be done with the value.

Cover-up table: tap a grey cell to check yourself.

TypeHoldsExamples
whole numbers42, -3, 0
numbers with a fractional part3.75, -0.5, 4.0
exactly one character, in single quotes'A', '7', '@'
any number of characters, in double quotes"Hello", ""
one of two valuesTRUE, FALSE

Choose the type from what the data is and what you will do with it:

  • The number of pupils in a class is an integer: you never have half a pupil.
  • A price or a temperature is real: 2.49 or 36.6.
  • A grade letter is a char; a name is a string.
  • Whether a fee has been paid is Boolean: it is either TRUE or FALSE.
  • A phone number is a string, even though it is made of digits. It can start with 0 and contain spaces, and you never add phone numbers together.
Sort them
Choose the best data type for each item.

Tap an item, then the box it belongs in.

INTEGER
REAL
CHAR
STRING
BOOLEAN
3🔍 In detailPart 3 / 22

Input and output

A program talks to its user through input and output.

  • INPUT Age waits for the user to type something and stores it in the variable Age.
  • OUTPUT shows values on the screen. Several values can be joined with commas: OUTPUT "You have ", Lives, " lives left".
  • Before every input, output a prompt so the user knows what to type.

Pseudocode

OUTPUT "What is your name?"
INPUT Name
OUTPUT "How old are you?"
INPUT Age
OUTPUT "Hello ", Name
OUTPUT "Next year you will be ", Age + 1

Python

name = input("What is your name? ")
age = int(input("How old are you? "))
print("Hello", name)
print("Next year you will be", age + 1)
Fill the blanks
Complete the rules for input and output.

Before every INPUT, write an with a prompt. Several values in one OUTPUT are separated by . In Python, input() always returns a , so use to turn it into a whole number.

4📘 DefinitionPart 4 / 22

Sequence and selection with IF

The three building blocks of every programSequenceSelectionIteration: WHILEIteration: REPEATone step after anotherchoose one pathtest first: may run 0 timestest last: runs at least onceINPUT PriceCost ← Price * 2OUTPUT CostAge >= 18?YesNoTicket ← 10Ticket ← 6Is N > 0?YesN ← N - 1NoINPUT PINPIN = 1234?NoYes
Sequence runs straight down. Selection takes one of two paths. A WHILE loop tests first; a REPEAT loop tests last.

Every program, however large, is built from three structures: , and .

Sequence means the statements run one after another, in order. The order matters: you cannot output an average before the values have been added up.

Selection means the program chooses what to do next. An IF statement tests a condition that is TRUE or FALSE. In Cambridge pseudocode THEN and ELSE are indented two spaces, and every IF ends with ENDIF.

Pseudocode

OUTPUT "Your age?"
INPUT Age
IF Age >= 18
  THEN
    Ticket ← 10
  ELSE
    Ticket ← 6
ENDIF
OUTPUT "Ticket price: ", Ticket

Python

age = int(input("Your age? "))
if age >= 18:
    ticket = 10
else:
    ticket = 6
print("Ticket price:", ticket)

An IF does not need an ELSE. IF Score > HighScore THEN HighScore ← Score ENDIF does nothing at all when the condition is FALSE.

Check yourself: Age is 18. What does the program set Ticket to?
5🔍 In detailPart 5 / 22

Selection with CASE

When one variable is compared with several single values, a CASE statement is shorter and clearer than a chain of IFs. The cases are tested from the top; the first one that matches runs, and the rest are skipped. OTHERWISE catches everything else and must be last.

Pseudocode

OUTPUT "Choose 1, 2 or 3"
INPUT Choice
CASE OF Choice
  1 : OUTPUT "New game"
  2 : OUTPUT "Load game"
  3 : OUTPUT "Quit"
  OTHERWISE OUTPUT "Not an option"
ENDCASE

Python

choice = int(input("Choose 1, 2 or 3 "))
if choice == 1:
    print("New game")
elif choice == 2:
    print("Load game")
elif choice == 3:
    print("Quit")
else:
    print("Not an option")

Python 3.10 and later also has a match statement that works like CASE, but if, elif and else are what you will see most often.

Put them in order
Put this CASE statement in the right order.

Tap in the right order. Tap a placed one to take it back.

6🔍 In detailPart 6 / 22

Iteration: FOR, WHILE and REPEAT

Iteration means repeating. Choose the loop by asking: do I know how many times?

Cover-up table: tap a grey cell to check yourself.

LoopKindWhen the test happensUse it when
FOR … TO … NEXTcounts automaticallyyou know how many times before it starts
WHILE … DO … ENDWHILEbefore each repeat, so it may run 0 timesthe loop might not be needed at all
REPEAT … UNTILafter each repeat, so it runs at least oncethe body must happen once before you can test

Pseudocode

FOR Count ← 1 TO 5
    OUTPUT Count * 3
NEXT Count

FOR Count ← 10 TO 0 STEP -2
    OUTPUT Count
NEXT Count

Guess ← 0
WHILE Guess <> 7 DO
    OUTPUT "Guess my number"
    INPUT Guess
ENDWHILE

REPEAT
    OUTPUT "Enter your PIN"
    INPUT Pin
UNTIL Pin = 1234

Python

for count in range(1, 6):
    print(count * 3)

for count in range(10, -1, -2):
    print(count)

guess = 0
while guess != 7:
    guess = int(input("Guess my number "))

# Python has no REPEAT: run, then test, then break
while True:
    pin = int(input("Enter your PIN "))
    if pin == 1234:
        break

Notice the opposite conditions: WHILE keeps going while its condition is TRUE; REPEAT keeps going until its condition becomes TRUE. Python’s range(1, 6) stops before 6, so it gives 1 to 5.

Loops are where totalling and counting happen: Total ← Total + Value and Count ← Count + 1 inside the loop, both set to 0 before it (see chapter 7). This WHILE loop uses a total to add up the digits of a number:

Try it

Press Next step and watch MOD take the last digit and DIV chop it off, until Number reaches 0 and the WHILE test fails.

Match the pairs
Match each task to the best loop.

Tap one on the left, then its partner on the right.

7🔍 In detailPart 7 / 22

String handling

A string is a row of characterspositionpseudocodeindexPython1C02O13M24P35U46T57E68R7SUBSTRING("COMPUTER", 4, 3) → "PUT"Python: word[3:6] → "PUT"Start at position 4 and take 3 characters. LENGTH("COMPUTER") is 8.
Positions count from 1 in pseudocode and indexes from 0 in Python. The yellow boxes are SUBSTRING("COMPUTER", 4, 3).

A string is a row of characters, and there are four routines you need for working with one:

Cover-up table: tap a grey cell to check yourself.

PseudocodeWhat it givesPython
LENGTH(Word)the number of characterslen(word)
UCASE(Word)the string in upper caseword.upper()
LCASE(Word)the string in lower caseword.lower()
SUBSTRING(Word, Start, Length)a : Length characters from position Startword[start - 1 : start - 1 + length]

Pseudocode

Word ← "Computer"
OUTPUT LENGTH(Word)            // 8
OUTPUT UCASE(Word)             // COMPUTER
OUTPUT LCASE(Word)             // computer
OUTPUT SUBSTRING(Word, 4, 3)   // put

Python

word = "Computer"
print(len(word))      # 8
print(word.upper())   # COMPUTER
print(word.lower())   # computer
print(word[3:6])      # put

The syllabus allows the first character to be position 0 or position 1. Cambridge pseudocode normally starts at 1; Python always starts at 0, which is why SUBSTRING(Word, 4, 3) becomes word[3:6]. A Python slice stops before its second number.

Worked example

What does LENGTH("Data science") return?

  1. Count the letters of "Data": 4.
  2. The space between the words is a character too: 1.
  3. Count the letters of "science": 7.
  4. Answer: 4 + 1 + 7 = 12 characters.
Check yourself: What does SUBSTRING("Keyboard", 4, 5) return?
8🔍 In detailPart 8 / 22

Arithmetic, relational and logical operators

Cover-up table: tap a grey cell to check yourself.

KindOperatorsGives
Arithmetic+ − * / ^ (power), MOD, DIVa number
= < <= > >= <> (not equal)TRUE or FALSE
AND OR NOTTRUE or FALSE

As in maths, ^ is worked out first, then * and /, then + and −. Use brackets to make the order clear.

Logical operators join conditions. Mark >= 0 AND Mark <= 100 is TRUE only if both parts are. Day = 6 OR Day = 7 is TRUE if either is. NOT Found is TRUE when Found is FALSE.

Worked example

What is the value of 7 + 3 * 2 ^ 2?

  1. Power first: 2 ^ 2 = 4.
  2. Then multiply: 3 * 4 = 12.
  3. Then add: 7 + 12.
  4. Answer: 19. Working left to right instead would give 400, which is wrong.
True or false?
X is 8 and Y is 3. True or false?
X > 5 AND Y > 5
X > 5 OR Y > 5
NOT (X = Y)
X <> 8
9🔍 In detailPart 9 / 22

Nested statements

A is one written inside another: an IF inside a loop, an IF inside another IF, or a loop inside a loop. The syllabus may ask you to use up to three levels.

Pseudocode

FOR Pupil ← 1 TO 25
    OUTPUT "Mark?"
    INPUT Mark
    IF Mark >= 50
      THEN
        IF Mark >= 80
          THEN
            OUTPUT "Distinction"
          ELSE
            OUTPUT "Pass"
        ENDIF
      ELSE
        OUTPUT "Not yet"
    ENDIF
NEXT Pupil

Python

for pupil in range(25):
    mark = int(input("Mark? "))
    if mark >= 50:
        if mark >= 80:
            print("Distinction")
        else:
            print("Pass")
    else:
        print("Not yet")

Here an IF sits inside an IF, which sits inside a FOR loop: three levels. The inner IF is only reached when the mark is at least 50, so it only has to decide between Distinction and Pass.

A loop inside a loop runs the whole inner loop once for every single turn of the outer loop. With an outer loop of 3 and an inner loop of 4, the innermost statement runs 3 × 4 = 12 times. Nested loops are how you visit every cell of a two-dimensional array (see 8.2).

Check yourself: A pupil’s mark is 80. What does the nested IF output?
10📘 DefinitionPart 10 / 22

Procedures, functions and parameters

What happens when a subroutine is calledMain program1 OUTPUT "Start"2 CALL Stars(3)3 Total ← Area(4.0, 2.5)4 OUTPUT TotalPROCEDURE Stars(Count)output Count starsENDPROCEDUREFUNCTION Area(L, W)RETURN L * WENDFUNCTIONBlue: CALL passes 3 into Count, the procedure runs, then control comes back to line 3.Green: 4.0 and 2.5 go into L and W, and RETURN sends 10.0 back into line 3.
CALL jumps to the procedure and back. A function call jumps to the function, and RETURN brings a value back with it.

A subroutine is a named block of code, written once and used whenever it is needed. There are two kinds:

  • A does a job. You run it with CALL. It does not send a value back.
  • A works out a value and sends it back with RETURN. You use it inside an expression, without CALL.

A is a value passed into the subroutine when it is called. The syllabus uses up to three parameters, each with its data type.

Pseudocode

PROCEDURE Stars(Count : INTEGER)
    FOR Index ← 1 TO Count
        OUTPUT "*"
    NEXT Index
ENDPROCEDURE

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

CALL Stars(3)
Total ← Area(4.0, 2.5)
OUTPUT "Area is ", Total

Python

def stars(count):
    for index in range(count):
        print("*")

def area(length, width):
    return length * width

stars(3)
total = area(4.0, 2.5)
print("Area is", total)

Subroutines are defined at the start of the program. When CALL Stars(3) runs, the value 3 goes into Count, the procedure runs, and control comes back to the next line. When Area(4.0, 2.5) is reached, the function runs and its returned value, 10.0, takes the place of the call in the expression.

Worked example

Using the function Area above, what does OUTPUT Area(4.0, 5.0) + 1 display?

  1. Pass the values in: Length = 4.0, Width = 5.0.
  2. The function returns 4.0 * 5.0 = 20.0.
  3. The returned value replaces the call: 20.0 + 1.
  4. Answer: 21.
Match the pairs
Match each term to its description.

Tap one on the left, then its partner on the right.

11🔍 In detailPart 11 / 22

Local and global variables

Global and local variablesWhole programScore (global)PROCEDURE AddBonusMessage (local)can use Score andits own MessageFUNCTION DoubleResult (local)cannot see Message;AddBonus cannot see ResultA local variable is created when its subroutine starts and lost when it ends.
Score belongs to the whole program. Message and Result each live only inside their own subroutine.

Where a variable is declared decides where it can be used, called its scope.

  • A is declared in the main program. It can be used anywhere, including inside subroutines.
  • A is declared inside a procedure or function. It exists only while that subroutine runs and cannot be used anywhere else.

Pseudocode

DECLARE Score : INTEGER          // global

PROCEDURE AddBonus(Bonus : INTEGER)
    DECLARE Message : STRING     // local
    Score ← Score + Bonus
    Message ← "Bonus added"
    OUTPUT Message
ENDPROCEDURE

Score ← 10
CALL AddBonus(5)
OUTPUT Score       // 15
OUTPUT Message     // error: Message is local

Python

score = 10                # global

def add_bonus(bonus):
    global score          # Python must be told
    message = "Bonus added"   # local
    score = score + bonus
    print(message)

add_bonus(5)
print(score)      # 15
print(message)    # NameError: message is local

Local variables are the safer choice. Two subroutines can each have a local Index without interfering, and a subroutine that only uses its parameters and locals can be tested on its own and reused in another program. A global variable can be changed by any line anywhere, which makes errors hard to track down.

True or false?
Scope. True or false?
A local variable can be used anywhere in the program.
A procedure can change a global variable.
A local variable keeps its value after its procedure ends.
12🔍 In detailPart 12 / 22

Library routines: MOD, DIV, ROUND and RANDOM

17 sweets packed into bags of 5bag 1bag 2bag 3left overDIV(17, 5) → 3how many full bagsMOD(17, 5) → 2what is left overCheck: 3 × 5 + 2 = 17. In Python: 17 // 5 is 3 and 17 % 5 is 2.
DIV counts the full bags; MOD counts what is left over.

A is a ready-made subroutine that comes with the language. It has already been written and tested, so you can use it straight away. Four are in the syllabus:

Cover-up table: tap a grey cell to check yourself.

RoutineWhat it returnsExamplePython
DIV(X, Y)the whole-number part of X ÷ YDIV(17, 5) → 317 // 5
MOD(X, Y)the remainder of X ÷ YMOD(17, 5) → 217 % 5
ROUND(X, Places)X rounded to that many decimal placesROUND(17.456, 1) → 17.5round(17.456, 1)
RANDOM()a random number from 0 to 10.4831…random.random()

MOD has many uses. MOD(N, 2) = 0 tests whether N is even. MOD(N, 10) gives the last digit of N. To get a random whole number, scale RANDOM and round it: ROUND(RANDOM() * 5, 0) + 1 gives a whole number from 1 to 6.

Worked example

A farm packs 47 eggs into boxes of 6. Use DIV and MOD to find the full boxes and how many eggs are left over. Enter the number left over.

  1. Full boxes: DIV(47, 6) = 7, because 7 × 6 = 42.
  2. Left over: MOD(47, 6) = 47 − 42.
  3. Check: 7 × 6 + 5 = 47.
  4. Answer: 7 full boxes and 5 eggs left over.

Worked example

Month ← ROUND(RANDOM() * 11, 0) + 1 picks a month number. What is the largest value it can produce?

  1. RANDOM() returns a number from 0 to 1 inclusive, so the largest it can return is 1.
  2. 1 × 11 = 11, and ROUND(11, 0) = 11.
  3. Add 1: 11 + 1.
  4. Answer: 12. The smallest is 0 + 1 = 1, so every month from 1 to 12 is possible.
Dice give each number from 1 to 6 the same chance. RANDOM lets a program do the same, for games, quizzes that shuffle questions, and simulations.Photo: Schlurcher, CC BY 4.0, Wikimedia Commons
Match the pairs
Match each expression to its value.

Tap one on the left, then its partner on the right.

13🌍 In the real worldPart 13 / 22

Writing a maintainable program

Programs are read far more often than they are written. Months later, someone (perhaps you) has to fix a bug or add a feature. A maintainable program is one that is easy to understand and change. The syllabus names three habits:

  • Meaningful identifiers for variables, constants, arrays, procedures and functions: PriceWithTax says what it holds, x does not.
  • that explain what each section does and why, written with // in pseudocode and # in Python.
  • Procedures and functions, so each task is written once, has a clear name, and can be tested and changed in one place.

Both programs below do exactly the same thing. Which would you rather fix?

Hard to maintain

INPUT a
b ← a + a * 0.15
OUTPUT b

Easy to maintain

// Adds sales tax to a price typed by the user
CONSTANT TaxRate ← 0.15

FUNCTION AddTax(Price : REAL) RETURNS REAL
    RETURN Price + Price * TaxRate
ENDFUNCTION

OUTPUT "Price before tax?"
INPUT Price
PriceWithTax ← AddTax(Price)
OUTPUT "Price with tax: ", PriceWithTax

When the tax rate changes, the second version needs one edit to one clearly named constant. The first needs someone to work out what 0.15 means.

Margaret Hamilton in 1969, next to printed listings of the Apollo guidance software that her team at MIT wrote. Code for a Moon landing had to be read and checked by many people, so its structure and comments mattered as much as the instructions.Photo: Adam Cuerden, Public domain, Wikimedia Commons
Sort them
Does each habit make a program easier or harder to maintain?

Tap an item, then the box it belongs in.

Easier
Harder
14🎯 Check yourselfPart 14 / 22

Check yourself: programming concepts

Subtopic 2 of 3

8.2 Arrays

4 parts
15📘 DefinitionPart 15 / 22

One-dimensional arrays

DECLARE Names : ARRAY[1:6] OF STRING[1]"Ana"[2]"Ben"[3]"Chen"[4]"Dev"[5]"Eli"[6]"Fay"indexvalueNames[4] → "Dev"With Index ← 4, Names[Index] is the same box. One name, many values, each reached by its index.
One name, six boxes. The index picks the box.

Storing the names of 30 pupils in 30 separate variables would be painful. An holds many values of the same type under one name. Each value is reached by its , the number of its position.

Pseudocode

DECLARE Names : ARRAY[1:6] OF STRING
Names[1] ← "Ana"
Names[4] ← "Dev"
OUTPUT Names[4]          // Dev
Index ← 4
OUTPUT Names[Index]      // also Dev
Names[Index + 1] ← "Eli"

Python

names = [""] * 6        # indexes 0 to 5
names[0] = "Ana"
names[3] = "Dev"
print(names[3])         # Dev
index = 3
print(names[index])     # also Dev
names[index + 1] = "Eli"

The declaration gives the lowest and highest index, here 1 to 6. Cambridge pseudocode usually starts at 1; Python lists always start at 0, so Names[4] in pseudocode is names[3] in Python.

Why are arrays so useful? Because the index can be a variable. Names[Index] means "whichever box Index points to", so one line inside a loop can reach every item in turn. Without arrays, sorting or searching a list would be almost impossible.

Parallel arrays. Several 1D arrays can hold different facts about the same things, kept at the same index: Names[3] and Ages[3] both belong to the third pupil.

Numbered post office boxes. Each box holds one person’s mail and is found by its number, just as each array element is found by its index.Photo: Joe Mabel, CC BY-SA 3.0, Wikimedia Commons
Check yourself: DECLARE Temps : ARRAY[1:7] OF REAL. Which statement stores 21.5 in the last element?
16🔍 In detailPart 16 / 22

Two-dimensional arrays

DECLARE Scores : ARRAY[1:3, 1:4] OF INTEGERsecond index: column (round)first index: row (player)12341121592021811161437191310Scores[2, 3] → 16 (row 2, column 3)
Row index first, then column index: Scores[2, 3] is 16.

A is a table with rows and columns. It needs two indexes: row first, then column.

Pseudocode

DECLARE Scores : ARRAY[1:3, 1:4] OF INTEGER
Scores[2, 3] ← 16
OUTPUT Scores[2, 3]      // 16
Player ← 3
Round ← 1
OUTPUT Scores[Player, Round]

Python

# a list of 3 rows, each a list of 4 columns
scores = [[0] * 4 for row in range(3)]
scores[1][2] = 16
print(scores[1][2])      # 16
player = 2
round_no = 0
print(scores[player][round_no])

Use a 2D array when every item has two "coordinates": scores for each player in each round, seats by row and seat number, marks for each pupil in each subject, the squares of a game board.

A 2D array holds one data type only. To keep names (strings) with scores (integers), use a 1D array of names alongside a 2D array of scores, linked by the same row index. That is exactly the design in June 2024 Paper 21 Question 10 and Specimen Paper 2B Question 13.

Match the pairs
Using the grid in the diagram, match each element to its value.

Tap one on the left, then its partner on the right.

17✏️ Worked examplePart 17 / 22

Filling and reading arrays with loops

Arrays and loops belong together. A FOR loop’s counter becomes the index, so the same few lines visit every element, whether there are 5 or 5000.

Pseudocode

// write values into a 1D array
FOR Index ← 1 TO 30
    OUTPUT "Name of pupil ", Index
    INPUT Names[Index]
NEXT Index

// read them back out
FOR Index ← 1 TO 30
    OUTPUT Names[Index]
NEXT Index

// a 2D array needs a loop inside a loop
FOR Player ← 1 TO 3
    FOR Round ← 1 TO 4
        INPUT Scores[Player, Round]
    NEXT Round
NEXT Player

Python

names = []
for index in range(30):
    names.append(input(f"Name of pupil {index + 1} "))

for index in range(30):
    print(names[index])

scores = [[0] * 4 for p in range(3)]
for player in range(3):
    for round_no in range(4):
        scores[player][round_no] = int(input())

With nested loops, the inner loop finishes all its turns for each turn of the outer loop: player 1’s four rounds, then player 2’s four rounds, and so on. Step through this one, which adds up each row of a small 2 by 3 array called Marks holding 4, 7, 2 in row 1 and 9, 0, 5 in row 2:

Try it

Press Next step. Notice that Col runs 1, 2, 3 for row 1, then starts again at 1 for row 2, and that RowTotal is reset to 0 at the start of each row.

Worked example

Using the Scores array in the 2D diagram above, a loop adds up every round for player 3. What total does it output?

  1. Row 3 holds Scores[3, 1] to Scores[3, 4]: 7, 19, 13 and 10.
  2. Start with Total ← 0 and add each one: 7, then 26, then 39.
  3. Add the last: 39 + 10.
  4. Answer: 49.
Fill the blanks
Complete the loop that finds the total of the 1D array Prices[1:10].

Total starts at . The loop runs from 1 TO . Each time round, the element at position is added to .

18🎯 Check yourselfPart 18 / 22

Check yourself: arrays

Subtopic 3 of 3

8.3 File handling

4 parts
19📘 DefinitionPart 19 / 22

Why programs store data in files

A program and its data fileProgram running in RAMHighScore ← 940Name ← "Rio"Scores.txt on storage940RioWRITEFILEREADFILElost when the program endsstill there next time
WRITEFILE copies data from a variable into the file; READFILE copies it back into a variable.

Variables and arrays live in RAM. When the program ends, or the power goes off, they are gone. A is kept on secondary storage, so its data is still there next time. Storing data in a file means:

  • data is kept permanently, between runs of the program: high scores, settings, saved games;
  • data does not have to be typed in again each time the program runs;
  • data can be shared: one program can write a file that another program, or another person, reads later;
  • a program can work on more data than it would be sensible to type in by hand.
True or false?
Files. True or false?
Data in variables is kept after the program closes.
A file lets data be used again the next time the program runs.
One program can read a file that another program wrote.
20🔍 In detailPart 20 / 22

Opening, reading, writing and closing a file

Working with a file always follows the same three steps: open it in a mode, read or write, then close it.

Cover-up table: tap a grey cell to check yourself.

PseudocodeWhat it does
OPENFILE "Scores.txt" FOR WRITEcreates a new, empty file ready for writing; any data already in it is lost
OPENFILE "Scores.txt" FOR READopens an existing file ready for reading
WRITEFILE "Scores.txt", HighScorewrites the value of a variable into the file
READFILE "Scores.txt", HighScorereads the next item or line from the file into a variable
CLOSEFILE "Scores.txt"closes the file when it is no longer needed

Pseudocode

// save a single item and a line of text
DECLARE HighScore : INTEGER
DECLARE Motto : STRING
HighScore ← 940
Motto ← "Practice makes progress"
OPENFILE "Game.txt" FOR WRITE
WRITEFILE "Game.txt", HighScore
WRITEFILE "Game.txt", Motto
CLOSEFILE "Game.txt"

// later: read them back in the same order
OPENFILE "Game.txt" FOR READ
READFILE "Game.txt", HighScore
READFILE "Game.txt", Motto
CLOSEFILE "Game.txt"
OUTPUT "Best so far: ", HighScore
OUTPUT UCASE(Motto)

Python

high_score = 940
motto = "Practice makes progress"
with open("Game.txt", "w") as f:
    f.write(str(high_score) + "\n")
    f.write(motto + "\n")

with open("Game.txt", "r") as f:
    high_score = int(f.readline())
    motto = f.readline().strip()
print("Best so far:", high_score)
print(motto.upper())

A file is opened in only one mode at a time. To read back what you have just written, close the file and open it again FOR READ. Items come back in the order they were written. Python’s with block closes the file for you at the end of the block.

Put them in order
Put the steps for saving a name to a file in order.

Tap in the right order. Tap a placed one to take it back.

21⚠️ Common mistakesPart 21 / 22

Common programming mistakes

Tap each trap and say the fix before you look
True or false?
Spot the mistake. True or false?
CALL Area(4.0, 2.5) is the right way to use a function.
Opening an existing file FOR WRITE keeps the data already in it.
A REPEAT loop always runs its body at least once.
22🎯 Check yourselfPart 22 / 22

Check yourself: file handling

Key terms in this chapter

30 terms, A to Z. Tap a term for the full explanation, or cover the right-hand side and test yourself.

A data structure that holds a fixed number of values of the same data type under one name, each reached by an index.
A data type with only two values, TRUE and FALSE.
A data type for one single character, written between single quotes.
A note in the code for human readers, which the computer ignores. Pseudocode comments start with //.
A named value that is set when it is declared and cannot be changed while the program runs.
A loop that repeats a set number of times, written FOR … TO … NEXT.
The kind of data a variable holds, which decides what values it can store and what can be done with it.
A named collection of data kept on secondary storage, so it lasts after the program closes.
A named subroutine that works out one value and returns it to the place it was called from.
A variable declared in the main program that can be used anywhere in the program, including inside subroutines.
The name given to a variable, constant, array, procedure or function.
The number that says which item of an array you mean.
A data type for whole numbers, positive, negative or zero.
Repeating a group of statements, using a loop.
A ready-made, tested subroutine that comes with the language and can be used straight away.
A variable declared inside a procedure or function. It can only be used there and is lost when the subroutine ends.
AND, OR and NOT, which join or reverse conditions.
A statement written inside another, such as an IF inside a loop or a loop inside a loop.
A value passed into a procedure or function when it is called, used inside it like a variable.
A loop that tests its condition after each repeat, written REPEAT … UNTIL. It always runs at least once.
A loop that tests its condition before each repeat, written WHILE … DO … ENDWHILE. It may not run at all.
A named subroutine that carries out a task. It is run with CALL and does not return a value.
A data type for numbers that can have a fractional part.
An operator that compares two values and gives TRUE or FALSE: =, <>, <, <=, > and >=.
Choosing which statements to run depending on a condition, using IF or CASE.
Statements carried out one after another in the order they are written.
A data type for a sequence of zero or more characters, written between double quotes.
Part of a string, taken from a start position for a given number of characters.
An array arranged as a table of rows and columns, with two indexes for each item.
A named place in memory that holds a value which can change while the program runs.

Reference material

Official papers to practise on, the same topic in other syllabuses, and trusted places to read more. Links open in a new tab.

Official Cambridge material

The same topic in other syllabuses

Read and practise more

Practise Programming

Everything on QuizByt for O Level Computer Science that goes with this lesson: read it first, then test yourself while it is fresh.

🧠 11 quizzes on Programming (6 easy, 3 medium, 2 hard)

One of them is open to everyone, no account needed. Work up from easy to hard: the hard quizzes ask the O Level exam-style questions on Programming.

🖨️ Printable worksheet

Programming on paper for O Level, with room to write the working out. Preview the first page free.

🎮 Games for O Level Computer Science

Memory and reasoning games at the right level for O Level. Passing a quiz on Programming earns the credits that open them.

Now test yourself

The quiz on this topic is one of our free ones, no account needed.

Your score is not saved without an account. Create a free one to keep your progress.