2.2.3 Additional programming techniques
This topic gathers the extra tools you need to write real programs: working with text, saving data in files, storing lots of values in arrays, splitting a program into sub programs and picking random numbers. All code here is in the OCR Exam Reference Language, which is the style used in the exam.
String manipulation
Characters in a string are numbered from 0. In "ComputerScience" the letter C is at position 0.
| Letter | C | o | m | p | u | t | e | r | S | c | i | e | n | c | e |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Position | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 |
Length, slicing and case
Taking part of a string is called slicing. These are the commands you need.
subject = "ComputerScience"
print(subject.length) // 15
print(subject.substring(3, 5)) // puter
print(subject.left(4)) // Comp
print(subject.right(3)) // nce
print(subject.upper) // COMPUTERSCIENCE
print(subject.lower) // computerscience
Concatenation
first = "Sam"
message = "Hi " + first + "!"
print(message) // Hi Sam!
You cannot join a number to a string directly. Cast the number to a string first with str().
score = 12
print("Score: " + str(score)) // Score: 12
Character codes
ASC() gives the character code of a letter and CHR() turns a code back into a character. You do not need to remember any codes.
print(ASC("A")) // 65
print(CHR(97)) // a
Worked example: initials
Task: The string name holds "Maya Patel". Build the initials "MP". The space is at position 4, so the surname starts at position 5.name = "Maya Patel"
initials = name.left(1) + name.substring(5, 1)
print(initials) // MP
name.left(1) is "M". name.substring(5, 1) starts at position 5 and takes 1 character, "P". Joined together they give "MP".
File handling
A program loses its variables when it ends. A file keeps data on storage so it can be used again later. The steps are open, read or write, then close.
| Command | What it does |
|---|---|
| open("sample.txt") | Opens the file so the program can use it |
| readLine() | Reads the next line of the file as a string |
| writeLine("text") | Writes a line to the end of the file |
| endOfFile() | True when there are no more lines to read |
| close() | Closes the file |
| newFile("myText.txt") | Creates a new, empty file |
Reading a file
myFile = open("sample.txt")
while NOT myFile.endOfFile()
print(myFile.readLine())
endwhile
myFile.close()
The loop keeps going until every line has been read. Each pass reads one line and prints it.
Writing to a file
newFile("log.txt")
logFile = open("log.txt")
logFile.writeLine("Game started")
logFile.writeLine("Level 1 done")
logFile.close()
After this program runs, log.txt holds two lines: Game started, then Level 1 done.
Records
Think of a table. Each row is one record and each column is one field. This table stores players.
| ID | Name | Team | Goals |
|---|---|---|---|
| 1 | Aisha | Reds | 7 |
| 2 | Ben | Blues | 3 |
| 3 | Chloe | Reds | 9 |
| 4 | Dev | Greens | 3 |
| 5 | Ella | Blues | 5 |
There are 5 records and 4 fields. The record for Chloe is: 3, Chloe, Reds, 9. A collection of records like this is the basis of a database table.
SQL
SQL is a language for searching a database. At GCSE you only need three commands: SELECT, FROM and WHERE.Use * to mean every field. In the conditions you can use = and the comparison signs > < >= <= and !=, and you can join conditions with AND and OR. Put text in double quotes.
SELECT * FROM Players WHERE Team = "Reds"
This shows every field of the records where Team is Reds: the rows for Aisha and Chloe.
SELECT Name FROM Players WHERE Goals > 4
This shows only the Name field for players with more than 4 goals: Aisha, Chloe and Ella.
SELECT Name, Goals FROM Players WHERE Team = "Blues" AND Goals > 3
With AND both conditions must be true. Ben is in Blues but has 3 goals, so only Ella, 5 appears.
SELECT Name FROM Players WHERE Team = "Greens" OR Goals = 3
With OR at least one condition must be true. Ben has 3 goals. Dev is in Greens and also has 3 goals. The result is Ben and Dev, and Dev appears once.
Arrays
Fixed length means the size is set when the array is made and cannot grow or shrink while the program runs.
One-dimensional (1D) arrays
array colours[5] // makes room for 5 items, index 0 to 4
array colours = ["Blue", "Pink", "Green", "Yellow", "Red"]
print(colours[2]) // Green
colours[0] = "Black" // changes the first item
for i = 0 to 4
print(colours[i])
next i
The loop prints every item in turn: Black, Pink, Green, Yellow, Red. Notice that for i = 0 to 4 includes 4.
Worked example: adding up an array
Task: Add up the values in marks.array marks = [6, 9, 4, 7]
total = 0
for i = 0 to 3
total = total + marks[i]
next i
print(total)
| i | marks[i] | total |
|---|---|---|
| start | 0 | |
| 0 | 6 | 6 |
| 1 | 9 | 15 |
| 2 | 4 | 19 |
| 3 | 7 | 26 |
The program prints 26.
Two-dimensional (2D) arrays
A 2D array is like a table. It has rows and columns, so you need two indexes: the row, then the column. A 2D array can stand for a table of records and fields, with each row as a record and each column as a field.
array gameboard[8,8] // 8 rows and 8 columns
gameboard[1,0] = "Pawn" // row 1, column 0
Worked example: quiz scores
Task: Store two quiz scores for each of 3 pupils, then print them all.array scores[3,2]
scores[0,0] = 5
scores[0,1] = 8
scores[1,0] = 7
scores[1,1] = 6
scores[2,0] = 9
scores[2,1] = 4
print(scores[2,0]) // 9
for row = 0 to 2
for col = 0 to 1
print(scores[row,col])
next col
next row
The first print shows 9, which is row 2, column 0. The nested loops then print 5, 8, 7, 6, 9, 4. The outer loop picks a row and the inner loop goes along its columns.
Sub programs
| Procedure | Function |
|---|---|
| Does a job | Does a job |
| Does not give a value back | Returns a value |
| Called as a statement on its own | Called where a value is needed, for example on the right of an = sign |
procedure greet(name)
print("Hello " + name)
endprocedure
function squared(number)
squared = number ^ 2
return squared
endfunction
greet("Sam") // prints Hello Sam
newValue = squared(4) // newValue is 16
The name in brackets in the first line is a parameter. The value you give when you call the sub program, such as "Sam" or 4, is an argument.
Why use sub programs
* Write once and use many times, so there is less code to type.
* The main program is shorter and easier to read.
* Each sub program can be tested on its own.
* A team can share the work, with each person writing different sub programs.
* A change only needs to be made in one place.
Local and global variables and constants
const vat = 0.2
global userID = "Cust001"
procedure showUser()
greeting = "Welcome "
print(greeting + userID)
endprocedure
showUser() // Welcome Cust001
price = 50
print(price * vat) // 10
Here greeting is local to showUser. The rest of the program cannot use it, and it is gone when the procedure ends. userID is global, so showUser can read it. vat is a constant, so its value is fixed.
| Advantages of local variables | Disadvantages of global variables |
|---|---|
| Other parts of the program cannot change them by accident | Any part of the program can change them, which makes errors hard to find |
| The same name can be reused in different sub programs | They stay in memory for the whole program |
| Memory is freed when the sub program ends | A sub program that depends on them is harder to reuse |
Passing and returning arrays
An array can be passed into a sub program as a parameter, and a function can return an array.
function biggest(nums)
top = nums[0]
for i = 1 to 3
if nums[i] > top then
top = nums[i]
endif
next i
return top
endfunction
array data = [4, 11, 7, 2]
print(biggest(data)) // 11
Trace: top starts at 4. 11 is bigger, so top becomes 11. 7 and 2 are smaller, so top stays 11. The function returns 11.
function doubleAll(nums)
array result[3]
for i = 0 to 2
result[i] = nums[i] * 2
next i
return result
endfunction
array small = [1, 2, 3]
bigger = doubleAll(small)
print(bigger[2]) // 6
Random number generation
The random() command gives a whole number between two values. Both ends are included.
dice = random(1, 6) // 1, 2, 3, 4, 5 or 6
coin = random(0, 1) // 0 or 1
pick = colours[random(0, 4)] // a random item from a 5-item array
Random numbers are used in games (dice, shuffling, enemy moves), simulations and testing with made-up data.
Exam technique
* State or give: one short fact, such as "A function returns a value."
* Describe: say what happens, step by step. For a program, say what it does overall, not each line.
* Explain: give a reason as well, for example why a local variable is safer.
* Compare: write about both sides, such as a function and a procedure, and use a linking word like "whereas".
* Trace or state the output: write the values in a table as you go and do not skip a loop.
* Write, complete or correct an algorithm: use the reference language or a high-level language. Plain English or bullet points earn no marks. Check that arrays start at 0, that loops end at the right value and that endif, endwhile, next i and endfunction are all there.
* SQL: SELECT fields, FROM table, WHERE condition, in that order.