GCSEPaper 2Programming fundamentalsAdditional programming techniques
2.2.3

Additional programming techniques

String handling, arrays, files, records, SQL, sub-programs and random numbers.

Learning Objectives

  • 1Manipulate strings, including concatenation and slicing
  • 2Use 1D and 2D arrays to solve problems, understanding they are fixed-length structures
  • 3Use records and 2D arrays to represent database-style tables of fields
  • 4Use basic file handling operations: open, read, write, close
  • 5Use SQL (SELECT, FROM, WHERE) to search for data
  • 6Use functions and procedures, including parameters, local and global variables
  • 7Generate random numbers in a program

String manipulation

You can manipulate strings (text) in several ways: joining two strings together (concatenation), finding how many characters are in a string (length), and pulling out part of a string (slicing).
Required string skills include concatenation (joining strings together, using +) and slicing (extracting part of a string). In OCR's Exam Reference Language, subject.length gives the number of characters, subject.substring(x, i) extracts i characters starting at position x (0-indexed), .left(i) and .right(i) get the first/last i characters, and .upper/.lower convert case.
Strings are 0-indexed, so the first character of a string is at position 0. In subject.substring(x, i), remember x is the starting index and i is the number of characters to extract, not an end index, a common error is to treat the second argument as an end position.
Python· String manipulation: length, substring, concatenation, case
subject = "ComputerScience"
print(len(subject))          # 15
print(subject[3:8])          # "puter" (substring: start 3, 5 chars)
print(subject[:4])           # "Comp" (left 4)
print(subject[-3:])          # "nce" (right 3)
print(subject.upper())       # "COMPUTERSCIENCE"
greeting = "Hi" + " there"   # concatenation
OCR ERL· String manipulation: length, substring, concatenation, case
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"
greeting = "Hi" + " there"     // concatenation

One-dimensional (1D) arrays

An array stores a fixed-size collection of items of the same data type under one name. Each item has an index (position), starting at 0. A 1D array is a simple list, like a row of boxes.
An array is a fixed-length (static) data structure, its size cannot change once declared, unlike a dynamic list. A 1D array is a single row of items, all of the same data type, each accessed by its index, starting at 0. For example, colours[1] accesses the second item in the array.
Arrays being static is a frequently examined fact, this means an array's size is fixed at declaration and cannot grow or shrink at run-time, unlike Python's built-in lists, which are dynamic. When working in Python for this specification, lists are used to represent arrays, but you should still describe arrays conceptually as fixed-length in written answers.
Python· Declaring and using a 1D array
scores = [10, 20, 30]
print(scores[1])   # 20
scores[0] = 15
OCR ERL· Declaring and using a 1D array
array scores = [10, 20, 30]
print(scores[1])   // 20
scores[0] = 15

Two-dimensional (2D) arrays

A 2D array is like a grid or table, an array of arrays. You need two indexes to find an item: one for the row, one for the column.
A 2D array can be thought of as a table or grid, useful for representing things like a game board or a set of database-style records. To access an item, you need two indexes: the row, then the column. In OCR's Exam Reference Language this is written as gameboard[1,0] (both indexes inside one set of square brackets, separated by a comma).
Syntax for indexing a 2D array differs between OCR's Exam Reference Language and Python: ERL uses a single pair of brackets with both indexes separated by a comma, e.g. seating[0,1], while Python uses two separate pairs of brackets (a list of lists), e.g. seating[0][1]. Both mean the same thing: row 0, item 1 within that row. Know which syntax you're using and stay consistent.
A 2D array is a gridColumn index →012Row index →0AdamAleksEnis1KrishTomMaxseating[0][1]First index: row 0Second index: item 1 in that row→ "Aleks"Both the row index and the column index start at 0, so the first item is [0][0].
Python· Accessing a 2D array: row 0, column 1
seating = [["Adam", "Aleks"], ["Krish", "Tom"]]
print(seating[0][1])   # "Aleks"
OCR ERL· Accessing a 2D array: row 0, column 1
array seating = [["Adam", "Aleks"], ["Krish", "Tom"]]
print(seating[0,1])   // "Aleks"

Records

A record groups together different pieces of related data as one unit, like a single row in a table. Unlike an array, the different fields in a record can have different data types.
A record is a data structure that groups several related fields together, similar to one row of a database table. Each field can hold a different data type, for example a student record might combine a string (name), an integer (year group), and a Boolean (has paid). The specification requires you to be able to use 2D arrays to emulate (represent) database tables made up of records and fields.
A record is best described as an entire row of data, e.g. [1, "Platinum", "Saturday", 0.5], containing one value for every field in that row. This was a notably poorly-answered exam question, many candidates could not correctly identify or construct an example of a record, despite records being explicitly named in the specification.
Python· A record: one row of related fields (stored as a 1D array). Stacking records makes a 2D array table.
student = ["Aleks", 10, True]   # one record: name, year group, has-paid
print(student[0])   # "Aleks" (the first field)
OCR ERL· A record: one row of related fields (stored as a 1D array). Stacking records makes a 2D array table.
array student = ["Aleks", 10, True]   // one record: name, year group, has-paid
print(student[0])   // "Aleks" (the first field)

File handling

File handling means reading data from, or writing data to, a file stored outside the program. A file must be opened before use and closed afterwards.
Required file handling operations are: open (start working with a file, storing it in a variable), read a line, write a line, and close (finish working with the file). In OCR's Exam Reference Language: myFile = open("sample.txt"), myFile.readLine(), myFile.writeLine("text"), and myFile.close().
A file must always be closed after use, if it isn't, changes made to it may not be saved correctly, and the file may remain locked for other programs to use. .endOfFile() can be used in a loop condition to keep reading lines until the end of the file is reached, without knowing in advance how many lines it contains.
Python· Reading every line from a file until the end
my_file = open("sample.txt", "r")
line = my_file.readline()
while line:
    print(line)
    line = my_file.readline()
my_file.close()
OCR ERL· Reading every line from a file until the end
myFile = open("sample.txt")
while NOT myFile.endOfFile()
    print(myFile.readLine())
endwhile
myFile.close()

SQL: searching a database

SQL (Structured Query Language) is used to search for data in a database. The three commands you need are SELECT (which fields you want), FROM (which table), and WHERE (a condition to filter the results).
An SQL query takes the form SELECT <field(s)> FROM <table> WHERE <condition>. Multiple fields are separated by commas, and the wildcard * means "all fields". String values in a WHERE condition must be enclosed in quotation marks, e.g. WHERE Day = "Saturday".
SQL is case-insensitive, keywords do not have to be capitalised, though capitals are used in exam papers by convention. Table and field names must not contain spaces. A very commonly examined error set: field names must be separated by commas (not AND), string values must be delimited with quotation marks, and the correct keyword for filtering is WHERE, not IF.
Python· Table: Cars(Model, Manufacturer, Price, Sold), find unsold cars
# SQL is written the same way regardless of host language
query = 'SELECT Model FROM Cars WHERE Sold = False'
OCR ERL· Table: Cars(Model, Manufacturer, Price, Sold), find unsold cars
SELECT Model
FROM Cars
WHERE Sold = False

Functions and procedures

A sub-program is a named, reusable block of code that performs a task. A function performs a task and gives back (returns) a value. A procedure performs a task but does not return a value. Which should you use? Pick a function when you need a value back to use later, such as working out a total. Pick a procedure when you just want something done, such as printing a menu on screen.
Subprograms make code more structured, reusable, and easier to test. Values passed into a sub-program are called parameters. A function always returns a value, which should be used (e.g. stored in a variable) by the code that called it. A procedure carries out a task, such as printing something, but does not return a value. Choosing between them: use a function where the calling code needs a value back to store or use in a further calculation, and a procedure where the task is complete in itself. Use a sub-program at all wherever the same task is needed in more than one place, or where a long program would be clearer broken into named steps.
Two specific, well-documented misconceptions: first, data should be passed into a sub-program via its parameters, not by asking for separate input inside the sub-program (which overwrites the parameter and ignores what was passed in); second, a function must return its result rather than printing it, and the code that calls the function must actually use the returned value (typically by assigning it to a variable), rather than redefining or recalculating it separately. Using sub-programs effectively means splitting a program at points where a task is genuinely self-contained and reused, so each sub-program has one clear job, can be tested on its own, and can be called from anywhere it is needed rather than the same code being written out repeatedly.
Python· A function returns a value; a procedure performs a task without returning one
def ticket_price(tickets):     # function: returns a value
    return tickets * 12.50

total = ticket_price(3)
print(total)

def greet(name):               # procedure: does a task, returns nothing
    print("Hello " + name)

greet("Sam")
OCR ERL· A function returns a value; a procedure performs a task without returning one
function ticketPrice(tickets)     // function: returns a value
    return tickets * 12.50
endfunction

total = ticketPrice(3)
print(total)

procedure greet(name)            // procedure: does a task, returns nothing
    print("Hello " + name)
endprocedure

greet("Sam")

Local and global variables

A local variable is created inside a sub-program and can only be used there, it disappears once the sub-program finishes. A global variable is created in the main program and can be used anywhere, including inside sub-programs.
Variables declared inside a function or procedure are local: they exist only while that sub-program is running, and cannot be accessed from outside it. Variables declared in the main body of the program are global: they can be read (and, if declared with the global keyword, updated) from anywhere in the program, including inside sub-programs.
Attempting to use a local variable outside the sub-program it was created in causes an error, since it no longer exists once that sub-program has finished executing. The global keyword explicitly declares or modifies a global variable. Arrays can also be passed into and returned from sub-programs, just like any other data type.
Python· d is local to the function; userMass is global; an array passed in and returned
def density(mass, volume):
    d = mass / volume   # d is local, only exists in this function
    return d

user_mass = float(input("Enter mass: "))   # global
user_volume = float(input("Enter volume: "))
user_density = density(user_mass, user_volume)
# print(d) here would cause an error, d does not exist outside the function

def double_values(values):        # an array can be passed into a sub-program...
    for i in range(len(values)):
        values[i] = values[i] * 2
    return values                  # ...and returned, just like any other data type

numbers = [1, 2, 3]
numbers = double_values(numbers)
OCR ERL· d is local to the function; userMass is global; an array passed in and returned
function density(mass, volume)
    d = mass / volume   // d is local, only exists in this function
    return d
endfunction

global userMass = real(input("Enter mass: "))
userVolume = real(input("Enter volume: "))
userDensity = density(userMass, userVolume)
// print(d) here would cause an error, d does not exist outside the function

function doubleValues(values, size)   // an array can be passed into a sub-program...
    for i = 0 to size - 1
        values[i] = values[i] * 2
    next i
    return values                      // ...and returned, just like any other data type
endfunction

array numbers = [1, 2, 3]
numbers = doubleValues(numbers, 3)

Random number generation

You can make a program generate a random number within a range, useful for things like dice rolls, games, or generating test data.
Random number generation produces an unpredictable value within a specified range, both bounds are usually inclusive. In OCR's Exam Reference Language, random(1, 6) generates a random integer between 1 and 6 inclusive (like a dice roll). If the value will be used more than once, store it in a variable rather than generating it again.
Random number generation is commonly combined with loops or selection for dynamic outcomes, for example simulating multiple dice rolls, or randomly selecting one of several possible outcomes in a game.
Python· Simulating a dice roll
import random
roll = random.randint(1, 6)
print(roll)
OCR ERL· Simulating a dice roll
roll = random(1, 6)
print(roll)

Exam Phrasing: Use These Exact Phrases

  • ✓An array is a fixed-length (static) data structure, indexed from 0
  • ✓A record groups related fields together as one unit, similar to a row in a table
  • ✓A function returns a value; a procedure does not
  • ✓A local variable only exists inside the sub-program it was created in; a global variable can be used anywhere
  • ✓SQL field names are separated by commas, and string values must be enclosed in quotation marks
  • 💡Remember arrays are fixed-length/static, this is a frequently tested fact, especially when comparing to Python lists.
  • 💡In SQL, use WHERE (not IF) to filter results, separate multiple fields with commas (not AND), and put string values in quotation marks.
  • 💡A record is best described as an entire row of related data, e.g. [1, "Platinum", "Saturday", 0.5], not just a single value.
  • 💡When defining a function, pass data in through its parameters, never ask for separate input inside it, and always return the result rather than printing it.
  • 💡When calling a function, actually use what it returns (e.g. assign it to a variable), don't redefine the function or recalculate the answer separately.
  • 💡Arrays can be passed into a sub-program as a parameter, and returned from one, exactly like any other data type.

Wrong:

SELECT Model FROM Cars IF Sold = "no"

Right:

SELECT Model FROM Cars WHERE Sold = False

Why it matters: SQL uses WHERE to filter results, not IF, and field/table names must not contain spaces.

Wrong:

A function asks for its own input instead of using its parameters

Right:

A function uses the values passed into it via its parameters

Why it matters: Asking for separate input overwrites the parameter and ignores the data the caller intended to pass in, losing marks.

Wrong:

A function prints its result instead of returning it

Right:

A function uses return to give back its result, which the caller can then use

Why it matters: Printing inside a function does not make the result available to the rest of the program, only returning it does.

Wrong:

Using a comma to join two strings together, e.g. message = word1, word2

Right:

Concatenate with +, e.g. message = word1 + word2

Why it matters: OCR examiners flagged this specifically. In most languages, and especially Python, a comma prints two separate items or passes two arguments, it does not concatenate them into one value. Examiners accept +, &, . or a sensible function such as concat(), but never a comma.

Wrong:

Writing for x in list, then trying to use list[x] later in the code

Right:

In that style of loop x is the item itself, not its index, so use x directly (or loop over the indexes instead if you need positions)

Why it matters: OCR examiners flagged this exact mistake. Treating the loop variable as an index when it is actually the value makes the rest of the code wrong.

Wrong:

An array can grow in size when new items are added

Right:

An array is fixed-length (static), its size cannot change once declared

Why it matters: This is a specifically, repeatedly examined fact, confused with Python's dynamic lists.

Question:

Define a function called ticketPrice that takes the number of tickets as a parameter, calculates the total cost (each ticket costs 12.50), and returns the result. Then show how the function would be called to calculate the price of 3 tickets, storing the result in a variable called total. [4]

Python· Model answer
def ticket_price(tickets):
    return tickets * 12.50

total = ticket_price(3)
print(total)
OCR ERL· Model answer
function ticketPrice(tickets)
    return tickets * 12.50
endfunction

total = ticketPrice(3)
print(total)

💡 Attempt this before revealing the answer, practice makes perfect!

Model Answer:

The function is defined with one parameter, tickets. Inside the function, the price is calculated by multiplying tickets by 12.50, and this value is returned using the return keyword. The function is then called with the argument 3, and the returned value is stored in the variable total using assignment.

Mark Scheme:

  • 1Function correctly defined with a parameter named tickets (not asking for separate input)
  • 2Correct calculation: tickets multiplied by 12.50
  • 3Result correctly returned using return, not printed
  • 4Function correctly called with 3, and the result assigned to the variable total

Tap a card to flip it. Use the arrow keys to move and space to flip.

Known 0 Still learning 0
1 / 13

Exam-style questions. Have a go, then reveal the mark scheme to check your answer.

1.Give an example of a record from a table storing book loans, with fields for BookID, Title, and OnLoan.

[1]

2.Explain why an array is described as a "static" or "fixed-length" data structure.

[2]

3.A candidate defines a function to calculate the area of a rectangle, but instead of using the given parameters width and height, the function asks the user to input them again. Explain why this is incorrect.

[2]

4.Write an SQL query to select the Title and Author fields from a table called Books, where the Genre field is "Fantasy".

[3]

5.Define a function called rectangleArea that takes width and height as parameters and returns the area. Show how it would be called to store the area of a rectangle with width 5 and height 3 in a variable called result.

[4]
Python· Model answer
def rectangle_area(width, height):
    return width * height

result = rectangle_area(5, 3)
OCR ERL· Model answer
function rectangleArea(width, height)
    return width * height
endfunction

result = rectangleArea(5, 3)

6.A program stores the seating plan for a classroom of 5 rows with 6 seats in each row. Explain why a 2D array is a suitable structure, and describe how a specific seat would be accessed.

[6]

The examiners' reports are the most useful and least read of the three: they say what candidates actually got wrong each year. All files are hosted by OCR.

Past-paper questions grouped by topic

The same OCR questions, sorted by topic rather than by year (via Physics & Maths Tutor).

2025
Paper 2

Only a small percentage of candidates could give a correct example of a record, such as an entire row of a database table (e.g. [1, "Platinum", "Saturday", 0.5]). This was the lowest scoring question on the entire paper, despite records being an explicitly named, required part of the specification (2.2.3).

Paper 2

In an SQL question, most candidates identified that the table name and filtering keyword needed correcting (IF should be WHERE), but far fewer replaced an incorrect AND between field names with a comma, or noticed missing quotation marks around a string value. SQL is case-insensitive so candidate answers do not need capitals, but field/table names must never contain spaces.

Paper 2

When defining and using functions, a common misconception was either omitting a parameter in the function definition, or overwriting/ignoring a given parameter by asking for separate input inside the function instead. Another common misconception was printing the calculated result instead of returning it. When later asked to use the function, many candidates redefined the function again or calculated the result a different way, instead of calling the function and using its returned value.

2024
Paper 2

In a question involving iterating through an array to implement a linear search, most candidates correctly identified the loop bounds and the value to return if the item was found, but fewer correctly used the loop's counter variable as the index into the array, this is a more advanced skill combining arrays with count-controlled loops that centres are encouraged to practise together.