KS48525 3.2.6 to 3.2.9 28 min read 10 question quiz 16 exam marks

Data Structures, Strings and Files

Arrays and records, every string operation AQA can ask for, reading and writing text files, and generating random numbers, with the traps that cost marks in each.

Arrays and records

An array is a data structure holding many values of the same type under one identifier, with each value found by its index.

OCR reference language
scores ← [14, 9, 21, 6, 18]
OUTPUT scores[0]
scores[3] ← 11

Indexing starts at 0, so the five items above are at positions 0, 1, 2, 3 and 4. There is no position 5, and asking for one is an out of range error.

Why arrays exist

Without an array, thirty scores means thirty separately named variables and thirty near identical lines of code. With an array, one loop handles any number of items and nothing breaks when the number changes.

OCR reference language
total ← 0
FOR i ← 0 TO LEN(scores) - 1
    total ← total + scores[i]
ENDFOR
LEN gives the number of items, not the last index

A five item array has LEN 5 and a last index of 4. Looping TO LEN(scores) runs one step too far. This single mistake accounts for a large share of runtime errors in exam code.

Two dimensional arrays

A two dimensional array is an array of arrays, useful for anything grid shaped: a seating plan, a game board, a table of results.

OCR reference language
board ← [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
OUTPUT board[1][2]

The first index selects the row, the second selects the position within it, so board[1][2] is 0.

Records

A record holds several values of different types that belong together, each with its own field name.

OCR reference language
student.name ← 'Amira'
student.year ← 10
student.average ← 68.4

An array holds many of the same thing. A record holds the several different things that describe one thing. A common structure is an array of records: one entry per student, each with a name, a year and an average.

Arrays and records: one index, two indexes, or a nameArrays and records. A one dimensional array is a row of values of the same type, reached by a single index, and the indexes start at zero, so in the row 4, 9, 2, 7, 1 the value at index 3 is 7. A two dimensional array is a grid of rows and columns, reached by two indexes, and the order is always row first and column second: in a three by three grid, grid index one index two means the second row and the third column, which here holds 6. A record is different: it holds a group of fields that can be of different types, such as a text name, an integer age and a boolean, and each field is reached by its name rather than by a position.One dimensionTwo dimensionsA record4091227314index starts at 0numbers[3]= 7one index finds one value123456789001122column →row ↓grid[1][2]= 6row first, then columnSTUDENTname"Asha"textage15integermemberTruebooleanstudent.namesame type, one rowsame type, rows and columnsdifferent types, by name1234
  1. A one dimensional array: values in a row, reached by one index.
  2. A two dimensional array: rows and columns, reached by two.
  3. grid[1][2] means row 1, then column 2. Row always comes first.
  4. A record holds fields of different types, reached by name.
Row first, then column. Say it out loud every time you write a 2D index and you will stop getting it backwards.

String handling

AQA names a specific set of string operations, and the exam expects you to use them by name.

OperationMeaningExample on "Computing"
LEN(s)Length in characters9
POSITION(s, c)Index of the first occurrence of a characterPOSITION('Computing', 'p') gives 3
SUBSTRING(a, b, s)The characters from index a to index b inclusiveSUBSTRING(0, 2, 'Computing') gives 'Com'
ConcatenationJoining strings together'Comp' + 'uting' gives 'Computing'
STRING_TO_INTConverts a string to an integer'25' becomes 25
INT_TO_STRINGConverts an integer to a string25 becomes '25'
CHAR_TO_CODEThe character set code for a character'A' becomes 65
CODE_TO_CHARThe character for a code65 becomes 'A'

String indexes also start at 0, so in "Computing" the C is at index 0 and the g is at index 8.

Converting case with character codes

Because the codes for the letters are in order and the gap between an upper case letter and its lower case partner is always 32, you can change case with arithmetic alone.

OCR reference language
code ← CHAR_TO_CODE(letter)
IF code ≥ 65 AND code ≤ 90 THEN
    letter ← CODE_TO_CHAR(code + 32)
ENDIF

That is not a curiosity. It is the sort of question AQA sets to check you understand that characters are numbers underneath.

A string is a row of characters, each with an indexThe word Computer drawn as eight letter tiles. Above each tile is its index, counting from 0 at the first letter to 7 at the last, and below it is the negative index, counting back from the end, from minus 8 to minus 1. A slice takes part of the string: word, bracket, 0, colon, 3 gives Com, which runs from index 0 up to but not including index 3, and word, bracket, 3, colon gives puter, from index 3 to the end. word minus one is the last character, r. Below, four things you can do with a string: len gives the number of characters, which is 8; upper gives a new string in capitals; find gives the index of the first match, here 3 for the letter p; and a plus sign joins two strings together. A string is never changed in place: each of these gives back a new string.indexfrom the endC0-8o1-7m2-6p3-5u4-4t5-3e6-2r7-1word[0:3] = "Com"word[3:] = "puter"word[-1] = "r"123len(word)8how many charactersword.upper()"COMPUTER"a new string in capitalsword.find("p")3index of the first matchword + "s""Computers"+ joins two strings4
  1. Every character has an index. The first is 0, and negative indexes count back from the end.
  2. A slice [a:b] runs from index a up to, but not including, b. Leave b out to go to the end.
  3. [-1] is the last character.
  4. Functions and methods build and search strings, and each one gives back a new string.
In exam pseudocode the same idea is written as substring: check your board's command set for the exact form.
Six string methods applied to the text with spaces round Hello World, and why the original never changesSix string methods applied to text equal to two spaces, Hello World, two spaces. upper gives all capitals. strip removes the spaces at the ends, giving Hello World. replace of l with capital L swaps every match, giving HeLLo WorLd with its spaces. strip then split on a space breaks the text into the list Hello, World. join of the list a, b, c with a hyphen builds the text a-b-c. find of World gives 8, the position where it starts. On the right a reminder that strings do not change: text dot upper makes a brand new string and leaves text as it was, so to keep the result you assign it, name equals name dot upper. Split and join are opposites.text = "  Hello World  "1text.upper()"  HELLO WORLD  "2text.strip()"Hello World"3text.replace("l", "L")"  HeLLo WorLd  "4text.strip().split(" ")["Hello", "World"]5"-".join(["a", "b", "c"])"a-b-c"6text.find("World")8Strings are fixed7textstays the sametext.upper() makesa brand new stringnew stringkeep it by assigning:name = name.upper()split and join are opposites: split breaks text into a list, join builds text from a list.
  1. upper() makes every letter a capital.
  2. strip() removes spaces from both ends.
  3. replace() swaps every match for something else.
  4. split() breaks a string into a list.
  5. join() builds a string from a list.
  6. find() gives the position of the first match, or -1 if there is none.
  7. A method returns a new string. The original is never changed unless you assign the result.
Methods return new strings. To keep the result, assign it to a variable.

Files and random numbers

Reading and writing text files

A program that forgets everything when it closes is of limited use. Writing to a file makes data persist.

OCR reference language
scores ← OPEN('results.txt')
line ← scores.readLine()
WHILE NOT scores.endOfFile()
    OUTPUT line
    line ← scores.readLine()
ENDWHILE
scores.close()

Three points get marks:

  • A file must be opened before use and closed afterwards. Not closing it can leave data unwritten, because output is often buffered.
  • Reading past the end of a file is an error, which is why a loop must test for the end of file.
  • Everything read from a text file arrives as a string, so numbers have to be converted before arithmetic.

Random numbers

OCR reference language
roll ← RANDOM_INT(1, 6)

Computers cannot produce genuinely random numbers. They produce pseudo-random numbers from an algorithm and a starting value called a seed, which means the same seed gives the same sequence every time.

Why pseudo-random matters

For a dice game it does not matter. For anything security related it matters enormously, because a predictable sequence means predictable keys. That is the reason AQA distinguishes the two words.

Reading, writing and appending to a text fileThree ways to open a text file, one card each. Opening with mode r reads the file: the program looks at the lines, nothing in the file changes, and it is an error if the file does not exist. Opening with mode w writes: it creates the file if it is missing, but if it exists everything in it is erased first, so a file that held two lines ends up holding only the new line. Opening with mode a appends: the new line is added to the end and the old lines are kept. The code below uses the with statement, which closes the file automatically, and writes the line Tia comma 51 followed by a newline character. Always close a file, because unwritten data may stay in a buffer and never reach the disk."r" readbeforeAsha,42Tom,37"w" writebeforeAsha,42Tom,37"a" appendbeforeAsha,42Tom,37programreads each linethe file is not changederror if it does not existTia,51erases what was therecreates the file if missingAsha,42Tom,37Tia,51adds to the endkeeps what was theresave.py1with open("scores.txt", "a") as f:2    f.write("Tia,51\n")with closes the file for you\n starts a new linea is safer than w for addingalways close a file, or the last lines may never reach the disk1234
  1. r reads. The file is only looked at, and it must already exist.
  2. w writes. Everything already in the file is erased first.
  3. a appends. New lines go on the end and the old ones are kept.
  4. with closes the file for you, and \n ends a line.
If you mean to add to a file, open it with a. Opening it with w by mistake wipes it.

Key terms you must be able to define

Array
A data structure holding multiple values of the same data type under one identifier, accessed by index.
Index
The position of an item within an array or string, counted from zero.
Two dimensional array
An array whose elements are themselves arrays, used to represent grids and tables.
Record
A data structure holding several related values of different data types, each in a named field.
Concatenation
Joining two strings together end to end.
SUBSTRING
An operation returning the characters of a string between two given positions.
Casting
Converting a value from one data type to another, such as a string to an integer.
End of file
The marker showing that there is no more data to read from a file.
Pseudo-random
Generated by an algorithm so that it appears random, but is fully determined by the starting seed.

Flashcards

Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.

DefineArray
AnswerA data structure holding multiple values of the same data type under one identifier, accessed by index.
DefineIndex
AnswerThe position of an item within an array or string, counted from zero.
DefineTwo dimensional array
AnswerAn array whose elements are themselves arrays, used to represent grids and tables.
DefineRecord
AnswerA data structure holding several related values of different data types, each in a named field.
DefineConcatenation
AnswerJoining two strings together end to end.
DefineSUBSTRING
AnswerAn operation returning the characters of a string between two given positions.
DefineCasting
AnswerConverting a value from one data type to another, such as a string to an integer.
DefineEnd of file
AnswerThe marker showing that there is no more data to read from a file.

Reach the top grade on this topic

The strongest answers here are the ones that keep types straight.

They say where data came from. Anything read from a file or from the user is a string until it is cast. Saying so explicitly is what turns a partially correct answer into a full one.

They count indexes carefully. Off by one errors are the single most common fault in exam code, and an answer that writes LEN(x) - 1 where it belongs shows the examiner that you understand indexing rather than remembering a pattern.

They choose the structure and justify it. "An array of records, because each student has several different pieces of information but every student has the same fields" is a complete answer. "An array" is half of one.

Mistakes that cost marks here

Avoid these
  • Looping FOR i to LEN(array) rather than LEN(array) - 1, which reads past the end.
  • Using an array for values of different types. That is a record's job.
  • Forgetting that data read from a file is a string and must be converted before arithmetic.
  • Forgetting to close a file, which can leave buffered output unwritten.
  • Saying computers generate random numbers. They generate pseudo-random numbers from a seed.
Fun fact

Almost every programming language counts array positions from zero rather than one. The reason is historical: early languages stored an index as an offset from the start of the block, and the first item sits zero places along.

Knowledge check

0 of 10 answered
1An array called names holds 6 items. What is the index of the last one?
2Which data structure would you use to store a student's name, year group and average mark together?
3What does SUBSTRING(2, 4, 'Computing') return?
4What is LEN('Computer Science')?
5Why must a number read from a text file be converted before it is used in a calculation?
6Why are computer generated random numbers described as pseudo-random?
7In a two dimensional array board, what does board[2][0] refer to?
8What is the value of CHAR_TO_CODE('B') if 'A' is 65?
9Why should a file be closed after a program has finished writing to it?
10A program needs the last digit of an integer n. Which expression gives it?
Score 0 / 10

Exam-style questions

Five written questions in the style of the real paper. Write a full answer, then let the marker check it against the mark scheme.

16 marks
1State one difference between an array and a record.2 marks
State

Mark scheme0 / 2
  • LAn array stores values that are all of the same data type
  • LA record stores values of different data types in named fields
Model answer

An array holds many values that must all be of the same data type, accessed by an index. A record holds several values of different data types that belong to one thing, each stored in its own named field.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2A program stores 30 test scores in an array called scores. Write an algorithm that outputs the highest score.4 marks
Write

Mark scheme0 / 4
  • LSets a starting highest value, for example the first element
  • LLoops through the array using the correct index range
  • LCompares each element with the current highest
  • LUpdates the highest and outputs it at the end
Model answer

Set highest to scores[0], then loop i from 1 to LEN(scores) minus 1. Inside the loop, if scores[i] is greater than highest then set highest to scores[i]. After the loop finishes, output highest. Starting from the first element rather than from zero matters, because a list of negative scores would otherwise report zero as the highest.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Explain why a program that reads a number from a text file must cast it before performing a calculation.3 marks
Explain

Mark scheme0 / 3
  • LA text file stores characters, so the value read is a string
  • LArithmetic operators do not behave as intended on strings
  • LCasting converts the string into an integer or real so the calculation works
Model answer

A text file holds characters, so a line read from it is a string even when every character in it is a digit. Applying an arithmetic operator to a string either causes an error or joins values together rather than adding them, so the result is wrong. Casting the string to an integer or a real converts it into a numeric value, after which the calculation behaves as intended.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4A programmer needs to store the names, ages and email addresses of 200 club members. Describe a suitable data structure and justify your choice.4 marks
Describe

Mark scheme0 / 4
  • LUses records to hold the three fields for one member
  • LJustifies the record because the fields have different data types
  • LUses an array to hold the 200 records
  • LJustifies the array because every member has the same set of fields and a loop can process them all
Model answer

The right structure is an array of records. Each member is one record with three named fields: name as a string, age as an integer and email as a string. A record is needed rather than an array for the individual member because the three values have different data types and belong together as a description of one person. The two hundred records are then held in an array, because every member has exactly the same set of fields, which means one loop can process all of them and the program does not have to change if the club gains or loses members.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Explain why pseudo-random numbers are unsuitable for generating encryption keys.3 marks
Explain

Mark scheme0 / 3
  • LThey are produced by an algorithm from a seed value
  • LThe same seed always produces the same sequence, so the numbers are predictable
  • LAn attacker who works out or guesses the seed can reproduce the keys
Model answer

Pseudo-random numbers come from a deterministic algorithm applied to a starting seed, so they only appear random. Give the algorithm the same seed and it produces exactly the same sequence every time. If an attacker can work out or guess the seed, perhaps because it was taken from the system clock, they can regenerate the whole sequence and therefore every key the program produced. Cryptographic use requires a source of genuine unpredictability rather than a repeatable formula.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 16