7 missions. Guess, learn, then check. Your place is saved.
Mission 1How does a game turn 135 seconds into 2:15 on its timer?
Mission 2How can a few lines of code print all 100 times-table answers?
Mission 3How can one name hold all 9 squares of a noughts and crosses board?
Mission 4Two subroutines both use a variable called total. Why no clash?
Mission 5How does an app show only the last 4 digits of your card number?
Mission 6You typed 41, not 14, for your age. Why did the form accept it?
Mission 7It passed every test. So why did it fail for an 18-year-old?
The specification points and sources are listed under the lesson: see Sources.
Mission 1
How does a game turn 135 seconds into 2:15 on its timer?
Make a guess: How does a game turn 135 seconds into 2:15 on its timer?
Programming · data and operators
Variables, constants, input and output
A variable is a named memory location whose value can change while the program runs.
A constant is a named value that cannot change while the program runs. Naming it means one place to update it, and clearer code.
Assignment puts a value into a variable; the first assignment is initialisation. Use meaningful identifiers like lives, not x.
Pearson pseudocode
CONST INTEGER MAX_LIVES
SET MAX_LIVES TO 3
SET lives TO MAX_LIVES
RECEIVE name FROM (STRING) KEYBOARD
SEND 'Good luck, ' & name TO DISPLAY
SET lives TO lives - 1
SEND lives TO DISPLAY
Programming · data and operators
Data types
A data type tells the computer what kind of data a variable holds and which operations make sense.
Data type
Holds
Examples
Integer
a whole number
42, -7, 0
Real
a number that can have a fractional part
3.5, -0.25, 12.0
Boolean
one of two values
True, False
Character
one single character
'A', '7', '@'
String
a sequence of characters
'Hello', '07700 900123'
Command-set keywords: INTEGER, REAL, BOOLEAN, CHARACTER; a STRING is treated as a data structure.
Quick check
?A program stores a customer's phone number, such as 07700 900123. Which data type is most suitable?
Programming · data and operators
Arithmetic operators
+, - and * work as in maths. Real division/ can give a fractional answer.
Integer division gives only the whole-number part. The remainder (modulus) is what is left over.
Operation
200 seconds ÷ 60
Result
Real division
200 / 60
3.333…
Integer division
200 DIV 60
3
Remainder
200 MOD 60
20
Pearson pseudocode
SET total TO 200
SET minutes TO total DIV 60 # 3
SET seconds TO total MOD 60 # 20
Calculate
?A shop packs eggs in boxes of 6. It has 47 eggs. What value does the program store in spare?
Pearson pseudocode
SET boxes TO 47 DIV 6
SET spare TO 47 MOD 6
Calculate
?What value is stored in result?
Pearson pseudocode
SET result TO 2 ^ 5
Programming · data and operators
Casting
Casting converts a value from one data type to another, e.g. the string '15' to the integer 15.
Keyboard input usually arrives as a string, so cast it before doing arithmetic.
Cast numbers to strings to join them into a message.
The command set calls this type coercion: integer + real gives a real (3 + 8.25 = 11.25), and RECEIVE … FROM (INTEGER) reads input as an integer.
Pearson pseudocode
RECEIVE age FROM (INTEGER) KEYBOARD
SEND age + 1 TO DISPLAY
SET total TO 3 + 8.25 # coerced to REAL: 11.25
Quick check
?A user types 15 for their age. The program reads it as a string and needs to output the age next year. What must happen first?
Mission check
?How does a game turn 135 seconds into 2:15 on its timer?
The timer keeps the time as one integer number of seconds. Integer division by 60 (DIV) gives the whole minutes, 2, and the remainder (MOD) gives the seconds left over, 15. Real division would give 2.25, which is not 2 minutes 25 seconds.
Mission 2
How can a few lines of code print all 100 times-table answers?
Make a guess: How can a few lines of code print all 100 times-table answers?
Programming · control flow
Sequence and selection
Sequence: statements run one after another, in order.
Selection: a condition that is true or false decides which block of code runs.
Compare with <, >, <=, >=, equal to = and not equal to <>.
Join conditions with AND, OR, NOT.
Pearson pseudocode
SET mark TO 72
IF mark >= 70 THEN
SEND 'Distinction' TO DISPLAY
ELSE
IF mark >= 40 THEN
SEND 'Pass' TO DISPLAY
ELSE
SEND 'Fail' TO DISPLAY
END IF
END IF
Quick check
?What is output when this code runs?
Pearson pseudocode
SET temp TO 18
SET wind TO 35
IF temp > 15 AND NOT (wind > 30) THEN
SEND 'Picnic' TO DISPLAY
ELSE
SEND 'Stay in' TO DISPLAY
END IF
Programming · control flow
Count-controlled loops
Iteration repeats a block of code.
A count-controlled loop repeats a fixed number of times. A counter variable goes up by 1 each time unless a step is given.
REPEAT 5 TIMES … END REPEAT is another count-controlled loop.
Pearson pseudocode
FOR count FROM 1 TO 5 DO
SEND count * 3 TO DISPLAY
END FOR
All output 3, 6, 9, 12, 15.
Programming · control flow
Condition-controlled loops
A condition-controlled loop repeats until a condition changes, so you need not know the number of passes.
A WHILE loop tests the condition at the start: it may run zero times.
REPEAT … UNTIL tests at the end, so it always runs at least once.
Pearson pseudocode
SET total TO 1
WHILE total < 50 DO
SET total TO total * 2
END WHILE
SEND total TO DISPLAY
All output 64.
Your answer
?What is output when this code runs?
Pearson pseudocode
SET n TO 3
WHILE n < 40 DO
SET n TO n * 2
END WHILE
SEND n TO DISPLAY
Programming · control flow
Nesting
Nesting puts one construct inside another: an IF inside a loop, a loop inside an IF, or a loop inside a loop.
With nested loops, the inner loop runs in full for every pass of the outer loop.
Total passes of the inner block = outer passes × inner passes.
Pearson pseudocode
FOR row FROM 1 TO 3 DO
FOR col FROM 1 TO 3 DO
SEND row * col TO DISPLAY
END FOR
END FOR
Output: 1, 2, 3, 2, 4, 6, 3, 6, 9 (9 values).
Calculate
?How many values does this code output?
Pearson pseudocode
FOR i FROM 1 TO 4 DO
FOR j FROM 1 TO 6 DO
SEND i + j TO DISPLAY
END FOR
END FOR
Mission check
?How can a few lines of code print all 100 times-table answers?
The program uses nested count-controlled loops. The outer loop counts the rows 1 to 10, and for every row the inner loop counts the columns 1 to 10 and outputs row × column. That gives 10 × 10 = 100 answers from a handful of lines.
Mission 3
How can one name hold all 9 squares of a noughts and crosses board?
Make a guess: How can one name hold all 9 squares of a noughts and crosses board?
Programming · data structures
Arrays
An array is a data structure: it stores many values under one identifier. Each value is an element.
All elements have the same data type.
An index picks out one element. The first element has index 0.
Pearson pseudocode
SET scores TO [12, 7, 9, 15, 4]
SEND scores[1] TO DISPLAY # 7
SET scores[3] TO 20 # 15 becomes 20
Programming · data structures
Looping through an array
Use a variable as the index in a count-controlled loop to visit every element in turn.
The counter runs from 0 to length − 1.
You can also loop over every item directly: FOR EACH t FROM temps DO.
Pearson pseudocode
SET temps TO [18, 21, 17, 22, 19]
SET total TO 0
FOR i FROM 0 TO LENGTH(temps) - 1 DO
SET total TO total + temps[i]
END FOR
SEND total TO DISPLAY
All output 97.
Your answer
?What is output when this code runs?
Pearson pseudocode
SET nums TO [0, 0, 0, 0, 0]
FOR i FROM 0 TO 4 DO
SET nums[i] TO i * 3
END FOR
SEND nums[2] + nums[4] TO DISPLAY
Programming · data structures
2D arrays
A two-dimensional (2D) array is like a table: one identifier, with rows and columns.
Each element needs two indexes: board[row, col] (row first here).
A noughts and crosses board is a 3 × 3 2D array of characters.
Pearson pseudocode
# board is a 3 x 3 array of characters
SET board[1, 1] TO 'X' # centre square
SET board[2, 0] TO 'O' # bottom-left square
Quick check
?This table shows a 2D array marks with 3 rows and 4 columns (row first). What is marks[1, 2]?
5
8
2
9
7
1
6
3
4
10
11
0
Programming · data structures
Records
A record groups related data about one item under one name.
Each item of data in a record is a field. Fields can have different data types.
Compare: an array's elements all share one data type, but a record mixes types.
Field
Data type
Example
name
String
'Biscuit'
species
String
'dog'
age
Integer
4
weight
Real
12.5
vaccinated
Boolean
True
Quick check
?A club stores each member's name, age and whether they have paid. Which structure best holds one member's details?
Mission check
?How can one name hold all 9 squares of a noughts and crosses board?
Store the board as a 2D array: one identifier, 3 rows × 3 columns, so 9 elements of the same data type. Each square is reached with two indexes, row then column, counting from 0.
Mission 4
Two subroutines both use a variable called total. Why no clash?
Make a guess: Two subroutines both use a variable called total. Why no clash?
Programming · subroutines
Subroutines
A subroutine is a named, out-of-line block of code. It runs when you call it by its name, then control returns to the line after the call.
A procedure carries out a task. A function carries out a task and returns a value.
Your board calls subroutines subprograms.
Pearson pseudocode
PROCEDURE welcome ()
BEGIN PROCEDURE
SEND 'Welcome to the quiz' TO DISPLAY
END PROCEDURE
welcome ()
welcome ()
Programming · subroutines
Parameters and return values
A parameter passes data into a subroutine when it is called. Values are matched to parameters in order.
A function sends its result back with return. The returned value replaces the call, so store it or use it straight away.
Pearson pseudocode
FUNCTION area (width, height)
BEGIN FUNCTION
SET result TO width * height
RETURN result
END FUNCTION
SET roomArea TO area (4, 5)
SEND roomArea TO DISPLAY # 20
Your answer
?What is output when this code runs?
Pearson pseudocode
FUNCTION change (paid, price)
BEGIN FUNCTION
RETURN paid - price
END FUNCTION
SEND change (20, 13) * 2 TO DISPLAY
Programming · subroutines
Local and global variables
A local variable is declared inside a subroutine: it only exists while that subroutine runs and is only usable inside it.
A global variable is declared in the main program and can be used anywhere.
Good practice: nothing outside can change a local variable, and its name can be reused elsewhere.
Pearson pseudocode
FUNCTION addBonus (score)
BEGIN FUNCTION
SET newScore TO score + bonus # newScore is local
RETURN newScore
END FUNCTION
SET bonus TO 5 # bonus is global
SEND addBonus (10) TO DISPLAY # 15
SEND newScore TO DISPLAY # error: newScore does not exist here
Quick check
?A subroutine calcTax declares a local variable tax and returns its value. After calling calcTax, the main program tries to output tax. What happens?
Programming · subroutines
Why use subroutines?
Reuse: write code once and call it many times, so there is less to write and check.
Decomposition: each subroutine solves one part and can be written and tested on its own.
Maintenance: fix or improve the code in one place.
Library routines are ready-made subroutines, e.g. LENGTH(), RANDOM(n).
Quick check
?Which task should be written as a function rather than a procedure?
Mission check
?Two subroutines both use a variable called total. Why no clash?
Each total is a local variable. It is created when its subroutine runs, can only be used inside that subroutine, and disappears when the subroutine ends. So the two variables never meet, which is why using local variables is good practice.
Mission 5
How does an app show only the last 4 digits of your card number?
Make a guess: How does an app show only the last 4 digits of your card number?
Programming · strings, files and random numbers
Strings have positions
A string is a sequence of characters. Each character has a position, its index.
The first character is at index 0, so the last is at length − 1.
The length of a string is how many characters it holds, spaces included.
A card number is stored as a string, not an integer: it is never used in arithmetic.
Pearson pseudocode
SET Card TO '4929123456789012'
SEND LENGTH(Card) TO DISPLAY
# displays 16
Programming · strings, files and random numbers
Taking a substring
A substring is part of a string, picked out by position.
Read characters one at a time by index, string[index], and join them with &.
Using the length makes the code work for any card length.
Pearson pseudocode
SET Card TO '4929123456789012'
SET Last4 TO ''
FOR Index FROM LENGTH(Card) - 4 TO LENGTH(Card) - 1 DO
SET Last4 TO Last4 & Card[Index]
END FOR
SEND '****' & Last4 TO DISPLAY
Your answer
?Trace this code. What is output?
Pearson pseudocode
SET Word TO 'computer'
SET Part TO ''
FOR Index FROM 3 TO 5 DO
SET Part TO Part & Word[Index]
END FOR
SEND Part TO DISPLAY
Programming · strings, files and random numbers
More string tools
& joins (appends) strings; a non-string joined with & becomes a string: 'Fred' & 18 gives 'Fred18'.
Programming · strings, files and random numbers
Random numbers
Games, quizzes and simulations need unpredictable values, such as a dice roll.
RANDOM(n) gives a number from 0 to n, so add 1 to start at 1.
Pearson pseudocode
SET Dice TO RANDOM(5) + 1
SEND Dice TO DISPLAY
Calculate
?How many different values can this code output?
Pearson pseudocode
SEND RANDOM(4) + 5 TO DISPLAY
Programming · strings, files and random numbers
Reading and writing files
Variables are lost when a program ends. A file in secondary storage keeps data, such as high scores, for next time.
Open the file, read or write it, then close it so the data is saved and the file is freed.
READ reads the next record from a file; WRITE writes a record to it.
Pearson pseudocode
WRITE Scores.txt 'Zara', 42
READ Scores.txt Record
SEND Record TO DISPLAY
Quick check
?A game keeps its high-score table in a variable. Every time the game closes, the scores vanish. What fixes this?
Mission check
?How does an app show only the last 4 digits of your card number?
The card number is stored as a string. The program finds its length, works out that the last four characters start at length − 4 when counting from 0 (length − 3 when counting from 1), and takes that substring to show after the stars.
Mission 6
You typed 41, not 14, for your age. Why did the form accept it?
Make a guess: You typed 41, not 14, for your age. Why did the form accept it?
Programming · validation and authentication
What validation does
Validation is an automatic check that input is sensible and follows rules before the program uses it.
Invalid data is rejected, and the user is told why and asked again.
It stops bad data causing crashes or wrong results later.
Validation cannot tell whether data is correct: a mistyped value that still follows the rules gets through.
Programming · validation and authentication
Types of validation check
Check
What it tests
Example
Range check
a number is between limits
age 0 to 120
Length check
number of characters
password at least 8
Presence check
something was entered (not empty)
surname not blank
Quick check
?A field for a 4-digit PIN accepted 12. Which check would have rejected it?
Programming · validation and authentication
Writing a validation routine
Ask for input, test it, and keep asking until it passes.
A loop does this: the user cannot move on with invalid data.
This WHILE loop is a range check for 1 to 10.
Pearson pseudocode
RECEIVE Score FROM (INTEGER) KEYBOARD
WHILE Score < 1 OR Score > 10 DO
SEND 'Must be 1 to 10' TO DISPLAY
RECEIVE Score FROM (INTEGER) KEYBOARD
END WHILE
Calculate
?The user types three names in this order: an empty string, Al, then Amir. How many times is "Too short" output?
Pearson pseudocode
RECEIVE Name FROM (STRING) KEYBOARD
WHILE LENGTH(Name) < 3 DO
SEND 'Too short' TO DISPLAY
RECEIVE Name FROM (STRING) KEYBOARD
END WHILE
SEND 'Hello ' & Name TO DISPLAY
Mission check
?You typed 41, not 14, for your age. Why did the form accept it?
Validation checks that data is reasonable, such as an age from 0 to 120. 41 follows that rule, so it is accepted even though it is wrong. Only a person who knows the right answer can spot that 41 is the wrong age.
Mission 7
It passed every test. So why did it fail for an 18-year-old?
Make a guess: It passed every test. So why did it fail for an 18-year-old?
Programming · testing
Why test?
Testing checks that a program works as intended and meets its requirements.
It finds errors so they can be fixed before users meet them.
A program can run without crashing and still give wrong results.
Passing a few easy tests proves little: choose test data that could expose errors.
Programming · testing
Normal, edge and wrong data
For a program that accepts whole numbers from 1 to 10:
Normal data: sensible values that should be accepted, e.g. 5.
Boundary data: values at the edges of the range, 1 and 10, and just outside them, 0 and 11.
Erroneous data: data that should be rejected, e.g. ten or 15.
Calculate
?The rule is "adult ticket for 18 and over". Tests with ages 10, 30 and 50 all gave the right ticket. Which single age would show the error?
Pearson pseudocode
RECEIVE Age FROM (INTEGER) KEYBOARD
IF Age > 18 THEN
SEND 'Adult ticket' TO DISPLAY
ELSE
SEND 'Child ticket' TO DISPLAY
END IF
Quick check
?A program accepts whole numbers from 1 to 10. A tester types the word ten. What type of test data is this?
Programming · testing
Types of error
A syntax error breaks the rules of the language, e.g. a missing bracket. The program cannot be translated or run.
A logic error lets the program run, but it gives the wrong or unexpected result, e.g. > where ≥ was needed.
A runtime error happens while the program runs and makes it crash, e.g. dividing by zero or using an index past the end of an array.
Testing with good test data is how you find logic errors.
Read the error message: it gives the error type and line number. Fix that line, then run again.
Quick check
?A program should output the average of three marks, 60, 70 and 80. It runs, but outputs 156.67 because the code says a + b + c / 3. What kind of error is this?
Programming · testing
Test plans
A test plan lists each test before it is run: what it tests, the test data, its type and the expected result.
After running, record the actual result. If they differ, fix the code and test again.
Test
Data
Type
Expected
Actual
1
5
Normal
Accepted
Accepted
2
10
Boundary
Accepted
Rejected
3
11
Boundary
Rejected
Rejected
4
ten
Erroneous
Rejected
Rejected
Test 2 failed, so the range check needs fixing.
Programming · testing
Code that is easy to maintain
Other people (and you, later) must be able to read and change code. This is maintainability.
Descriptive names: totalScore, not t.
Comments explain what each part of the code does.
Indentation shows which lines belong inside loops, selection and subprograms.
Subprograms break code into named, reusable parts.
Mission check
?It passed every test. So why did it fail for an 18-year-old?
The code used > 18 when the rule needed ≥ 18, a mistake that only shows at exactly 18. Testing 10, 30 and 50 only tried normal values; a test at the edge of the range would have caught it.
Recap
Big ideas
A variable is a named memory location whose value can change; a constant keeps one value while the program runs.
Choose the data type that fits the data: integer, real, Boolean, character or string, and cast between types when needed (input text to an integer).
Integer division gives the whole-number part; the remainder (modulus) gives what is left over.
Sequence runs statements in order; selection uses a true/false condition to choose a branch.
Count-controlled loops repeat a fixed number of times; condition-controlled loops repeat until a condition changes, tested at the start or the end.
In nested loops the inner loop runs fully for every pass of the outer loop.
An array holds many values of one data type under one identifier; an index picks out an element (the first is index 0).
A 2D array is a table of rows and columns, so each element needs two indexes.
A record groups fields of different data types about one item.
A subroutine is a named block of code called by its name; a function returns a value and a procedure does not.
Parameters pass data in, in order; return passes a result back to the call.
Local variables exist only inside their subroutine while it runs, so the same name can be reused safely; global variables can be used anywhere.
A string is a sequence of characters, each with an index; the length is how many characters it has. Indexes start at 0.
A substring picks out part of a string by position.
Files keep data after a program ends: open, read or write, close.
Random number functions give a value in a range, including both ends.
Validation automatically checks input is sensible, e.g. range, length and presence checks, and rejects data that breaks the rules; it cannot check data is correct.
Choose test data of every kind: normal, at the edges of the range, and data that should be rejected (normal, boundary, erroneous).
Syntax errors stop a program running; logic errors give wrong results; runtime errors crash it while it runs.
Meaningful names, comments, indentation and subprograms make code easy to maintain.
🏆
Mini-lesson complete!
⭐⭐⭐
You've worked through Programming for Pearson Edexcel International GCSE Computer Science (4CP0). 🎉
Mission 1How does a game turn 135 seconds into 2:15 on its timer?
Mission 2How can a few lines of code print all 100 times-table answers?
Mission 3How can one name hold all 9 squares of a noughts and crosses board?
Mission 4Two subroutines both use a variable called total. Why no clash?
Mission 5How does an app show only the last 4 digits of your card number?
Mission 6You typed 41, not 14, for your age. Why did the form accept it?
Mission 7It passed every test. So why did it fail for an 18-year-old?