Skip to content

2.2.3 Additional programming techniques

GCSE · Paper 2 · Computational thinking, algorithms and programming · Section 2.2 · 20 flashcards · 12 practice questions

Questions

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

Definition
A string is a sequence of characters. String manipulation means changing a string or taking part of it.

Characters in a string are numbered from 0. In "ComputerScience" the letter C is at position 0.

LetterComputerScience
Position01234567891011121314

Length, slicing and case

Taking part of a string is called slicing. These are the commands you need.

pseudocode
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
Key Point
substring(start, numberOfCharacters) takes two numbers: the position to start at, then how many characters to take. It does not take an end position. So subject.substring(3, 5) starts at position 3 and takes 5 characters: p, u, t, e, r.

Concatenation

Definition
Concatenation means joining strings together end to end, using the + operator.
pseudocode
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().

pseudocode
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.

pseudocode
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.
pseudocode
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.

Definition
File handling is opening a file, reading data from it or writing data to it, and then closing it.
CommandWhat 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

pseudocode
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

pseudocode
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.

Warning
Always close a file when you have finished with it. A file left open may not save everything that was written and can stop other programs using it. Remember that readLine() always gives you a string. Use int() or float() if the line holds a number.

Records

Definition
A record is a collection of related data about one thing. Each piece of data in a record is a field.

Think of a table. Each row is one record and each column is one field. This table stores players.

IDNameTeamGoals
1AishaReds7
2BenBlues3
3ChloeReds9
4DevGreens3
5EllaBlues5

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.
Definition
SELECT says which fields to show. FROM says which table to use. WHERE says which records to keep.

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.

sql
SELECT * FROM Players WHERE Team = "Reds"

This shows every field of the records where Team is Reds: the rows for Aisha and Chloe.

sql
SELECT Name FROM Players WHERE Goals > 4

This shows only the Name field for players with more than 4 goals: Aisha, Chloe and Ella.

sql
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.

sql
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.

Exam Tip
Write the fields after SELECT, the table after FROM and the condition after WHERE, in that order. Check the spelling of the field and table names against the table you are given.

Arrays

Definition
An array is a data structure that stores a fixed number of items of the same data type under one name. Each item has an index, and the first index is 0.

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

pseudocode
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.
pseudocode
array marks = [6, 9, 4, 7]
total = 0
for i = 0 to 3
    total = total + marks[i]
next i
print(total)
imarks[i]total
start0
066
1915
2419
3726

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.

pseudocode
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.
pseudocode
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

Definition
A sub program is a named block of code that does one job and can be called from other parts of the program. There are two kinds: procedures and functions.
ProcedureFunction
Does a jobDoes a job
Does not give a value backReturns a value
Called as a statement on its ownCalled where a value is needed, for example on the right of an = sign
pseudocode
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

Definition
A local variable is made inside a sub program and can only be used there. A global variable is declared with the word global and can be used anywhere in the program. A constant is given a value once, with const, and cannot change while the program runs.
pseudocode
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.

Pros & Cons
Advantages of local variablesDisadvantages of global variables
Other parts of the program cannot change them by accidentAny part of the program can change them, which makes errors hard to find
The same name can be reused in different sub programsThey stay in memory for the whole program
Memory is freed when the sub program endsA 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.

pseudocode
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.

pseudocode
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.

pseudocode
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.

Remember
Strings and arrays both count from 0. For i = 0 to 4 runs five times. substring takes a start position and a number of characters. random(1, 6) includes both 1 and 6.

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.