OCR GCSE COMPUTER SCIENCE · J277 · PAPER 2
Strings, arrays and records
Cut and join text, keep many values under one name, and group fields together.
Paper 2 · Lesson 24
Les van Computing
In deze les zitten 24 slides, met interactieve quizzen en tekstslides.
OCR GCSE COMPUTER SCIENCE · J277 · PAPER 2
Strings, arrays and records
Cut and join text, keep many values under one name, and group fields together.
Paper 2 · Lesson 24
Lesson 24 of the J277 series (Block D, Paper 2, section 2.2.3 Additional programming techniques): string manipulation, one- and two-dimensional arrays, records and random number generation.
Cover photo: Tim Wildsmith / Unsplash (hologram of numbered post office boxes: each box has its own number, like the index of an array element).
Device-free: show the slide; pupils write the title and date. Image credit: Tim Wildsmith / Unsplash (cover hologram)
00 · MISSION · BY THE END OF THIS LESSON
By the end of this lesson you can…
01 Use length, substring, upper, lower, concatenation, ASC and CHR on strings.
02 Store, read and loop through 1D and 2D arrays, starting at index 0.
03 Explain what a record is, and generate random numbers.
Read the three outcomes. J277 section 2.2.3 expects pupils to use string manipulation, one- and two-dimensional arrays, records to store data and random number generation, in OCR Exam Reference Language (ERL) or a high-level language such as Python.
Device-free: pupils copy the outcomes and tick each one at the end.
02 · CHECK · DO NOW (LESSON 23)
Warm up: selection and iteration
1 What does elseif do?
2 How many times does for i = 1 to 5 run?
3 Which numbers does Python range(1, 6) give?
4 Which loop always runs at least once?
▮ TERMINAL // do_now_answers
1 tests another condition, only
if every condition above was False
2 5 times (i = 1, 2, 3, 4, 5)
3 1 2 3 4 5 (stops before 6)
4 do ... until
(it checks at the end)
Retrieval from lesson 23. Give 4 minutes, then click to reveal the answers line by line.
1 elseif tests another condition, but only when every condition above it was False; only the first True branch runs. 2 Five times: in ERL, to 5 includes 5, so i = 1, 2, 3, 4, 5. 3 range(1, 6) gives 1, 2, 3, 4, 5: it stops before 6. 4 do ... until: the condition is checked at the end of each pass, so the body always runs at least once.
Today loops come back straight away: a for loop is how a program visits every element of an array.
Device-free: questions on the board; mini whiteboards.
Recap. A game loop is while lives > 0. lives starts at 0. How many times does the loop body run?
1
3
10
0
Answer: D, 0. A while loop checks its condition BEFORE each pass. 0 > 0 is False at the very first check, so the body never runs (checked in Python 3 with while lives > 0:).
1 is the do ... until answer: a do ... until loop would run once before checking. 3 and 10 have no link to the code.
Photo: Javier Martínez / Unsplash.
Device-free: students hold up A, B, C or D cards. Image credit: Javier Martínez / Unsplash
01 · LEARN · MISSION BRIEFING
Store the data
A variable holds one value. Today you meet three ways to hold more.
STRING
Characters in order. Cut it, join it, change its case.
ARRAY
Many values of one data type, under one name.
RECORD
Related fields together. Each field can be a different type.
SYSTEM VOICE
System online. Today's mission: store data. Cut and join strings, keep many values in one array, map a grid with a two-dimensional array, group fields into a record, and roll a random number.
Click play for the system voice briefing. The words are also on the slide.
A variable such as score holds one value. Real programs need more: a name is a string of characters; a class's 30 test scores belong together in an array; everything about one pupil (name, age, form, whether they have paid for a trip) belongs together in a record.
Quick hook: a music app stores each song title as a string, a playlist as an array of songs, and each song's details (title, artist, length in seconds) as a record.
Device-free: pupils write one example of each from an app they use.
01 · LEARN · STRING LENGTH AND SUBSTRING
Measure a string, and cut a piece out
▮ TERMINAL // strings.erl
1 word = "COMPUTER"
2 print(word.length)
3 print(word.substring(0, 3))
4 print(word.substring(5, 3))
> 8 > COM > TER
▮ TERMINAL // strings.py
1 word = "COMPUTER"
2 print(len(word))
3 print(word[0:3])
4 print(word[5:8])
> 8 > COM > TER
C O M P U T E R
0 1 2 3 4 5 6 7
ERL: substring(start, how many characters).
Python: word[start:stop] stops before stop. Both count from 0.
A string is a sequence of characters. Each character has a position (index), and the first one is 0: C is 0, O is 1, up to R at 7.
Left, OCR Exam Reference Language: word.length gives 8, the number of characters. word.substring(start, length) takes a START position and HOW MANY characters: substring(0, 3) starts at C and takes 3: COM. substring(5, 3) starts at index 5 (T) and takes 3: TER.
Right, Python (click to reveal; all three outputs checked in Python 3, each on its own line): len(word) gives 8. Slicing word[start:stop] uses a STOP position that is NOT included, like range(): word[0:3] gives indexes 0, 1, 2: COM. word[5:8] gives 5, 6, 7: TER.
Misconception to tackle: the second number means different things. ERL substring(5, 3) = 3 characters; Python word[5:3] would be an empty string.
Device-free: pupils write the ERL and the Python to get PUT from COMPUTER (substring(3, 3); word[3:6]).
01 · LEARN · MORE STRING TOOLS
Case, joining and character codes
▮ TERMINAL // text.erl vs text.py · name = "Ravi" · age = 15
ERL PYTHON OUTPUT
name.upper name.upper() RAVI
name.lower name.lower() ravi
name + " is " + str(age) name + " is " + str(age) Ravi is 15
ASC("A") ord("A") 65
CHR(66) chr(66) B
Case
ERL .upper has no brackets. Python .upper() needs them.
Concatenation
+ joins strings. str() turns a number into a string first.
Character codes
ASC gives a character's code. CHR turns a code into a character.
Each row shows the same job in ERL (left) and Python (middle), with what print() displays (right). Click to reveal row by row; ask for each output first. All Python outputs checked in Python 3.
Case: name.upper gives RAVI and name.lower gives ravi. In ERL .upper and .lower are written with no brackets; Python needs name.upper() and name.lower(). The original string is not changed.
Concatenation: + joins strings, so name + " is " + str(age) gives Ravi is 15. str(age) is needed because age is an integer: "Ravi" + 15 is an error in Python. Note the spaces inside " is ".
Character codes: ASC("A") gives 65, the ASCII code of capital A (lesson 6). CHR(66) gives "B". Python uses ord() and chr(). Capitals A to Z are 65 to 90; lower case a is 97.
Device-free: pupils work out ASC("C") (67) and CHR(68) (D), and write the line that prints Ravi is 15 years old.
01 · LEARN · ONE-DIMENSIONAL ARRAYS
An array holds many values under one name
▮ TERMINAL // scores.erl
1 array scores[5]
2 scores = [12, 7, 15, 9, 11]
3 total = 0
4 for i = 0 to 4
5 total = total + scores[i]
6 next i
7 print(total)
array scores[5] makes 5 spaces: indexes 0 to 4.
scores[i] reads the element at index i.
▮ TERMINAL // trace_table
i | scores[i] | total
---+-----------+-------
- | - | 0
0 | 12 | 12
1 | 7 | 19
2 | 15 | 34
3 | 9 | 43
4 | 11 | 54
output: 54
An array is a data structure that stores several values of the SAME data type under ONE name. In OCR ERL, array scores[5] declares a fixed-size array with 5 elements; line 2 fills it. Each element has an index, and the first index is 0, so the indexes are 0, 1, 2, 3 and 4.
Click to trace the loop, asking pupils for each value first. total = 0. i = 0: scores[0] is 12, total 12. i = 1: scores[1] is 7, total 19. i = 2: 15, total 34. i = 3: 9, total 43. i = 4: 11, total 54. The loop ends and line 7 outputs 54. (12 + 7 + 15 + 9 + 11 = 54, checked in Python 3.)
Why for i = 0 to 4 and not 1 to 5: the indexes run from 0 to 4. Starting at 1 would miss 12, and scores[5] does not exist.
Device-free: pupils copy the trace table, then trace the loop again with scores = [5, 10, 5, 10, 5] (total 35).
01 · LEARN · ARRAYS IN PYTHON
The first element is at index 0
scores
12
7
15
9
11
[0] [1] [2] [3] [4]
5 elements, indexes 0 to 4. scores[4] is the last one; scores[5] gives an error.
ERL fixes the size: array scores[5]. A Python list is used as the array.
▮ TERMINAL // scores.py
1 scores = [12, 7, 15, 9, 11]
2 total = 0
3 for i in range(5):
4 total = total + scores[i]
5 print(total)
6 print(scores[0], scores[4])
> 54
> 12 11
The diagram shows the array from the last slide: five elements in one row, each with its index underneath. The index is the position; the value is what is stored there. scores[2] is 15, not 7.
Right: the same program in Python (click to reveal line by line). Python has no array keyword; a list in square brackets is used as the array. range(5) gives 0, 1, 2, 3, 4: exactly the indexes. The output is 54, then 12 11 (print with two values puts a space between them). Checked in Python 3.
Arrays in the exam: OCR arrays are fixed size and hold one data type. Python lists can grow and mix types, but in the exam treat them like arrays. Asking for scores[5] in Python stops the program with an IndexError (index out of range).
Device-free: pupils answer on whiteboards: what is scores[3]? (9) Which index holds 15? (2)
01 · LEARN · TWO-DIMENSIONAL ARRAYS
A 2D array is a grid of rows and columns
col 0 col 1 col 2
row 0
row 1
row 2
4
9
2
3
5
7
8
1
6
board
Row first, then column.
board[1,2] is row 1, column 2: 7.
▮ TERMINAL // board.erl
1 array board[3,3]
2 print(board[1,2]) // 7
3 print(board[2,0]) // 8
▮ TERMINAL // board.py
1 board = [[4, 9, 2],
2 [3, 5, 7],
3 [8, 1, 6]]
4 print(board[1][2]) # 7
5 print(board[2][0]) # 8
A two-dimensional (2D) array is a grid: an array of rows, where each row is itself an array. It suits anything laid out in rows and columns: a game board, cinema seats, a timetable, the pixels of an image.
In OCR ERL, array board[3,3] declares 3 rows and 3 columns. To reach one element, give the ROW first, then the COLUMN, both counted from 0. board[1,2]: go to row 1 (the middle row), then column 2 (the right-hand column): 7, highlighted. board[2,0]: bottom row, first column: 8.
Python uses a list of lists, one inner list per row, and two pairs of brackets: board[1][2] is 7 and board[2][0] is 8 (checked in Python 3). The comments after // and # show what each line prints.
Exam tip: OCR questions usually tell you how the array is laid out. Read the question to see which index is the row; in this course we write board[row, column].
Fun fact: every row, column and diagonal of this grid adds to 15 (a magic square).
Device-free: pupils write the index of the 9 (board[0,1]) and the value at board[2,2] (6).
01 · LEARN · RECORDS
A record groups fields of different types
FIELD name age form paid
RECORD "Amara" 15 "10B" True
TYPE string integer string Boolean
HOW OCR TESTS IT
ERL has no record keyword. Records usually appear as rows of a database table: name the fields and choose a data type for each. SQL comes next lesson.
▮ TERMINAL // record.py
1 pupil = {"name": "Amara",
2 "age": 15,
3 "form": "10B",
4 "paid": True}
5 print(pupil["name"]) # Amara
6 print(pupil["age"] + 1) # 16
or one list per record:
7 pupil = ["Amara", 15, "10B", True]
8 print(pupil[1]) # 15
A record stores related data about ONE thing, such as one pupil. Each item is a field, and each field can have a DIFFERENT data type: name is a string, age an integer, form a string (10B has a letter), paid a Boolean. Compare an array, where every element has the same type.
How OCR examines it: OCR Exam Reference Language has no record keyword. Records are usually examined through databases: a table is a collection of records, each row is one record and each column is a field. Pupils may be asked to name a field, give a suitable data type for a field, or say how many records a table holds. Next lesson they search records with SQL.
In Python (click to reveal), a dictionary stores a record as field names and values: pupil["name"] gives Amara and pupil["age"] + 1 gives 16, because age is stored as an integer. Another way is one list per record, where each position is a field: pupil[1] is the age, 15. All outputs checked in Python 3.
Device-free: pupils design a record for a book in a library: four fields with a data type each (for example title string, price real, year integer, on loan Boolean).
01 · LEARN · RANDOM NUMBERS
Roll a dice in code
▮ TERMINAL // dice.erl
1 roll = random(1, 6)
2 print("You rolled " + str(roll))
> You rolled 4
(one possible run)
▮ TERMINAL // dice.py
1 import random
2 roll = random.randint(1, 6)
3 print("You rolled " + str(roll))
> You rolled 4
(one possible run)
Both ends are included: random(1, 6) and randint(1, 6) can give 1, 2, 3, 4, 5 or 6.
Every run can differ. Python needs import random first.
Pick a random array element with an index: names[random(0, 4)].
Random number generation is used in games, quizzes and simulations. OCR ERL: random(1, 6) gives a random whole number from 1 to 6, and BOTH ends are included. (OCR ERL also allows random(-1.0, 10.0) for a real number.)
Python: the random module must be imported first, then random.randint(1, 6) gives 1 to 6, again including both ends (unlike range). Checked in Python 3: 2000 rolls gave every value 1, 2, 3, 4, 5 and 6 and nothing else.
The output shown is one possible run: 4 here, but the next run might print You rolled 1 or You rolled 6. str(roll) is needed to join the number to the text.
Link to arrays: names[random(0, 4)] picks a random element from a 5-element array (indexes 0 to 4). In Python, names[random.randint(0, 4)].
Device-free: pupils write the ERL line for a random number from 1 to 100 (random(1, 100)) and the Python line for a coin toss with 0 and 1 (random.randint(0, 1)).
01 · LEARN · THE BIG IDEA
An array is numbered boxes
1 Each box is one element.
2 The number on the door is the index.
3 What is inside the box is the value.
4 Open any box straight away by its number: scores[3].
5 A wall of rows and columns is a 2D array.
Remember: in code the first box is number 0.
Click to reveal the points. The picture is the idea to remember: a wall of post office boxes, each with its own number on the door. To collect your post you go straight to your box by its number; you do not open every box. That is exactly how an array works: the number is the index, the post inside is the value, and scores[3] goes straight to the element at index 3.
The boxes are laid out in rows and columns, like a 2D array: board[row, column] names one box by its row and its column.
One difference: these doors start at 209, but in OCR ERL and Python the first index is always 0.
Photo: Stéphane Mingot / Unsplash.
Device-free: pupils draw five boxes, number them 0 to 4 and put the scores 12, 7, 15, 9, 11 inside. Image credit: Stéphane Mingot / Unsplash
01 · LEARN · WHICH STRUCTURE?
String, array or record?
STRING
Characters in order, counted from 0.
A postcode, a password.
ARRAY
Many values, one data type, one name. Fixed size.
30 test scores.
RECORD
Related fields about one thing, of different types.
One pupil: name, age, paid.
SYSTEM VOICE · KEY DEFINITION
Key definition. An array stores many values of the same data type under one name. Each value has an index, starting at zero. A record groups related fields, and each field can have a different data type.
Play the key definition, then go through the three cards.
String: a sequence of characters, such as a postcode or a password. Even a phone number or postcode with digits is a string, because nobody does maths on it. Array: many values of the same data type under one name, each found by its index; in OCR ERL an array has a fixed size. Record: several fields about ONE thing, such as one pupil, and the fields can have different data types.
Quick test: "the scores of 30 pupils" is an array (30 values, all integers). "One pupil's name, age and whether they have paid" is a record (one thing, mixed types).
Device-free: pupils write one new example of their own for each structure.
String, array or record? Drag each one to the best fit.
STRING
ARRAY
RECORD
30 test scores, all integers
One book: title, price, in stock or not
The names of the 5 players in a team
One pupil: name, age, form, paid
A postcode such as SW1A 1AA
A password the user types in
Answers. String: a postcode such as SW1A 1AA; a password the user types in (single pieces of text, made of characters). Array: 30 test scores, all integers; the names of the 5 players in a team (many values of the same type under one name). Record: one book with title, price and in stock or not; one pupil with name, age, form and paid (related fields about one thing, with different data types).
Discuss: the 5 player names are strings, but together they form an array of strings. Why is the book a record and not an array? Its fields have different types: title is a string, price is a real, in stock is a Boolean.
Device-free: pupils draw three columns and write each item in the right one.
word = "COMPUTER". What does word.substring(3, 3) return in ERL?
PUT
MPU
PUTE
UTE
Answer: A, PUT. substring(start, length): start at index 3, counting from C = 0 (C 0, O 1, M 2, P 3), and take 3 characters: P, U, T. In Python this is word[3:6], which gives PUT (checked in Python 3).
MPU starts at index 2: counting from 1 instead of 0. PUTE takes 4 characters, treating the second number as an end position plus one. UTE starts at index 4.
Photo: Anders Bengs / Unsplash.
Device-free: students hold up A, B, C or D cards. Image credit: Anders Bengs / Unsplash
Cinema seats are stored in seats[row, column], counting from 0. Which is the first seat in the third row?
seats[0,2]
seats[3,1]
seats[2,0]
seats[3,0]
Answer: C, seats[2,0]. Rows are counted 0, 1, 2, so the third row is row 2. The first seat in that row is column 0. Row comes first, then column. In Python this would be seats[2][0].
seats[0,2] swaps row and column (first row, third seat). seats[3,1] and seats[3,0] count from 1 instead of 0: row 3 is the fourth row.
Photo: Andrii Solok / Unsplash.
Device-free: students hold up A, B, C or D cards. Image credit: Andrii Solok / Unsplash
03 · DEBUG · SPOT THE MISTAKE
One comment in Kwame's code is wrong
▮ TERMINAL // kwame_strings.py
1 print(len("PYTHON")) # 6
2 print("PYTHON"[0:2]) # PY
3 print("PYTHON"[1:4]) # YTHO
4 print(ord("C")) # 67
Line 3. A slice stops before the stop index, so "PYTHON"[1:4] gives indexes 1, 2 and 3, which is YTH. To get YTHO, use [1:5].
Run each line in your head. Then tap the marker.
Tip: write the indexes under the letters: P 0, Y 1, T 2, H 3, O 4, N 5.
Give a minute to find the mistake before tapping the marker. The comments (after #) are Kwame's notes on what each line prints.
Answer: line 3. A Python slice stops BEFORE the stop index, so "PYTHON"[1:4] takes indexes 1, 2 and 3: Y, T, H, giving YTH. To get YTHO it must be [1:5]. In ERL the same task is "PYTHON".substring(1, 3) for YTH.
The other lines are correct (all four run in Python 3): len("PYTHON") is 6; [0:2] gives PY; ord("C") is 67, because A is 65, B 66, C 67.
Device-free: copy the four lines onto the board; pupils write the wrong line number and the correct output.
Set total to 0
Start the loop at index 0
Move on to the next index
Output total
Stop after the last index
Add the element at this index to total
Put the steps of totalling an array in the order they happen.
Correct order: 1 set total to 0; 2 start the loop at index 0; 3 add the element at this index to total; 4 move on to the next index; 5 stop after the last index; 6 output total.
In code: total = 0 (step 1), for i = 0 to 4 (steps 2, 4 and 5), total = total + scores[i] (step 3), next i, then print(total) (step 6). Common mistakes: setting total to 0 INSIDE the loop (it resets every pass), starting at index 1 (misses the first element) or printing inside the loop.
Device-free: pupils write the six steps on sticky notes and order them on the desk.
Complete the summary.
A string is a sequence of characters. In ERL, word.length gives how many characters it has. An array stores many values of the same data type under one name, and its first index is 0. A record groups fields that can have different data types. random(1, 6) gives a whole number from 1 to 6.
Answers in order: string, length, array, 0, record, 6. Distractors: 1, 5, field.
1 is the classic wrong first index. 5 is the range() habit, but random(1, 6) includes 6. A field is one part of a record, not the record itself.
Device-free: paragraph on the board with gaps and the word bank; pupils write the six missing words.
EXAM · An array scores holds 10 test scores. Write an algorithm that outputs the highest score. [4 marks]
Exam-style question, 4 marks. Give 6 minutes. Pupils may answer in OCR Exam Reference Language or Python. The array already holds the 10 scores (indexes 0 to 9). The model answer is on the next slide.
Mark scheme: 1 mark each. Sets a variable for the highest score before the loop (to the first element, scores[0], or to a value lower than any score, such as 0 or -1). Loops through every element of the array (index 0 to 9, or 1 to 9 if starting from scores[0]). Compares each element with the highest so far and replaces it when the element is bigger. Outputs the highest after the loop has finished.
Do not award the loop mark for a loop that runs to 10: scores[10] does not exist. Starting highest at 0 is fine for test scores, but would fail if every value could be negative.
Device-free: pupils answer on paper, then peer-mark with the next slide.
04 · EXAM · MODEL ANSWER
Keep the best so far
▮ TERMINAL // highest.erl
1 highest = scores[0]
2 for i = 1 to 9
3 if scores[i] > highest then
4 highest = scores[i]
5 endif
6 next i
7 print(highest)
Python: for i in range(1, 10): and if scores[i] > highest:
MARK SCHEME
1 mark: set highest before the loop
1 mark: loop through all 10 elements
1 mark: compare, and replace highest if bigger
1 mark: output highest after the loop
Python is also accepted.
Click to reveal the model answer line by line. highest starts as the first score, scores[0], so the loop can start at index 1 and check the other nine (indexes 1 to 9). Each score that is bigger than the best so far replaces it. After the loop, highest holds the largest value.
Trace with scores = [56, 72, 91, 45, 88, 67, 73, 91, 30, 64]: highest starts at 56, becomes 72 at index 1, then 91 at index 2; nothing later is bigger (the second 91 is not greater than 91), so the output is 91. Checked in Python 3, also with all-negative scores, where it correctly outputs the largest negative value.
Python version (also accepted): highest = scores[0], then for i in range(1, 10): with if scores[i] > highest: and highest = scores[i] indented underneath, then print(highest) back at the left margin.
Common mistakes: setting highest inside the loop, using < instead of >, looping to 10 (scores[10] does not exist) or printing inside the loop.
Device-free: pupils tick each mark-scheme point on their own answer and correct it in a different colour.
How sure are you about arrays and strings?
Very: I can index and loop through them
Fairly: substring still trips me up
Not yet: I need another go
Anonymous exit poll. If many pupils find indexes tricky, start lesson 25 by writing a word with its indexes underneath and asking for substrings and array elements again.
Device-free: thumbs up, sideways or down.
05 · NEXT · KEEP GOING
Keep going
Isaac Computer Science
Free online lessons and questions. Look for the topics on strings, arrays and records.
BBC Bitesize
GCSE Computer Science, OCR: revise string handling and arrays.
Try it in Python
Store 5 names in a list, then print a random one with random.randint(0, 4).
Next lesson: subprograms, file handling and SQL.
Point pupils to the places to practise. Isaac Computer Science and BBC Bitesize are free.
The Python challenge, as a model: import random, then names = ["Aisha", "Ben", "Chloe", "Dev", "Erin"], then print(names[random.randint(0, 4)]). It prints one of the five names, chosen at random each run. randint(0, 4) matches the indexes 0 to 4.
Device-free: pupils write the program on paper and say what could be printed, to bring to lesson 25.