What you'll learn
Programming techniques are the building blocks used to write every program. In OCR GCSE Computer Science (J277, section 2.2) you must know how to use variables, constants, operators, inputs, outputs and assignments; the three basic programming constructs — sequence, selection and iteration; the common arithmetic and comparison operators including MOD and DIV; data types and casting; string manipulation; file handling; the use of records and SQL to search for data; arrays (one- and two-dimensional); sub-programs (functions and procedures) and local and global variables; and random number generation. This guide explains each technique with examples in OCR Exam Reference Language.
Paper 2 asks you to read, complete, correct and write code. Section B includes questions where you write code in OCR Exam Reference Language or a high-level language. Precise syntax helps, but clear, correct logic is what earns the marks.
Key terms and definitions
Variable — A named location in memory that holds a value that can change while the program runs.
Constant — A named value that does not change while the program runs.
Assignment — Giving a variable a value, such as score = 0.
Sequence — Instructions executed one after another in order.
Selection — Choosing which instructions to execute based on a condition (if, switch/case).
Iteration — Repeating instructions: count-controlled (for) or condition-controlled (while, do…until).
Data type — The kind of data a variable holds: integer, real, Boolean, character or string.
Casting — Converting a value from one data type to another.
Array — A data structure that holds several values of the same type under one name, accessed by index.
Sub-program — A named block of code that performs a task; a function returns a value, a procedure does not.
Local variable — A variable declared inside a sub-program, only accessible within it.
Global variable — A variable accessible throughout the whole program.
SQL — Structured Query Language, used to search databases.
Core concepts
Variables, constants, input, output and assignment
const VAT = 0.2
name = input("Enter your name")
price = 50
total = price + price * VAT
print("Hello " + name + ", your total is " + str(total))
Using a constant for values such as VAT makes the program easier to read and update, and prevents the value being changed accidentally while the program runs.
Operators
Arithmetic: +, -, *, /, ^ (exponent), MOD (remainder) and DIV (whole-number division).
17 MOD 5= 217 DIV 5= 32 ^ 3= 8
MOD is useful for checking whether a number is even (n MOD 2 == 0) or for wrapping around values.
Comparison: == (equal to), != (not equal to), <, <=, >, >=.
Boolean: AND, OR, NOT.
The three constructs
Sequence — the order of instructions matters. Calculating a total before reading the inputs gives the wrong result.
Selection:
if mark >= 70 then
print("Grade 7")
elseif mark >= 50 then
print("Grade 5")
else
print("Keep practising")
endif
A switch/case statement selects between many fixed values:
switch choice:
case "A":
print("Add")
case "D":
print("Delete")
default:
print("Invalid")
endswitch
Iteration:
Count-controlled, used when the number of repetitions is known:
for i = 1 to 10
print(i * 7)
next i
Condition-controlled, used when it is not:
while guess != secret
guess = int(input("Guess"))
endwhile
A do … until loop always runs at least once, because the condition is checked at the end.
Data types and casting
| Data type | Example |
|---|---|
| Integer | 42 |
| Real (float) | 3.14 |
| Boolean | True / False |
| Character | "A" |
| String | "Hello" |
input() returns a string, so a number entered must be cast before calculation: age = int(input("Age")). Other casting functions include str(), float() and real(). Casting "12" to an integer gives 12; casting 12 to a string allows it to be joined (concatenated) to text.
String manipulation
If word = "Computer":
word.length→ 8word.upper→ "COMPUTER";word.lower→ "computer"word.substring(0, 3)→ "Com" (start position, number of characters)word.left(3)→ "Com";word.right(3)→ "ter"- Concatenation:
"Com" + "puter"→ "Computer" ASC("A")→ 65 andCHR(65)→ "A" convert between characters and their ASCII codes.
Positions start at 0.
File handling
myFile = open("scores.txt")
line = myFile.readLine()
myFile.close()
newFile = open("log.txt")
newFile.writeLine("Game over")
newFile.close()
Files allow data to persist after the program closes. Always close the file when finished. endOfFile() can be used in a loop to read every line.
Records and SQL
Data in a database is stored in tables made of records (rows) and fields (columns). SQL is used to search them:
SELECT Name, Score
FROM Players
WHERE Score > 100
SELECT names the fields to return, FROM names the table, and WHERE gives the condition. SELECT * returns all fields. Conditions can be combined with AND and OR, and LIKE with the wildcard % matches patterns, as in WHERE Name LIKE "S%" for names beginning with S.
Arrays
A one-dimensional array stores a list of values:
array scores[5]
scores[0] = 12
print(scores[0])
A two-dimensional array stores a table, accessed by two indexes:
array grid[3,3]
grid[1,2] = "X"
Loops are used to process every element:
total = 0
for i = 0 to 4
total = total + scores[i]
next i
Arrays in OCR Exam Reference Language are static — their size is fixed when declared — and indexes start at 0.
Sub-programs
Sub-programs make code reusable, easier to read, test and maintain, and allow work to be shared among programmers.
A procedure carries out a task but does not return a value:
procedure greet(name)
print("Hello " + name)
endprocedure
A function returns a value:
function area(length, width)
return length * width
endfunction
a = area(4, 5)
Values passed into sub-programs are parameters.
Local and global variables
A local variable is declared inside a sub-program and exists only while it runs. Local variables prevent accidental changes from elsewhere and allow the same name to be reused in different sub-programs. A global variable is accessible everywhere; it is convenient but can be changed unexpectedly by any part of the program, making errors harder to find. Good practice is to use local variables and pass values as parameters.
Random numbers
random(1, 6) generates a random integer between 1 and 6, useful for games, simulations and testing.
Putting the constructs together
Real programs combine sequence, selection, iteration, arrays and sub-programs. This short program reads five scores, validates each one, stores them in an array and reports the highest and the average:
function getScore()
s = int(input("Enter a score from 0 to 100"))
while s < 0 OR s > 100
s = int(input("Invalid. Enter 0 to 100"))
endwhile
return s
endfunction
array scores[5]
total = 0
highest = 0
for i = 0 to 4
scores[i] = getScore()
total = total + scores[i]
if scores[i] > highest then
highest = scores[i]
endif
next i
print("Highest: " + str(highest))
print("Average: " + str(total / 5))
Notice how each technique has a job: the function keeps validation in one reusable place, the while loop repeats until input is valid, the for loop processes each array element, the if statement tracks the highest value, and casting with str() lets numbers be joined to text. In the exam, being able to explain why each part is there is as valuable as writing it.
Nesting
Constructs can be placed inside one another. A loop can contain an if statement (as above), an if can contain another if, and loops can be nested — for example, two for loops are used to visit every element of a two-dimensional array, one for the rows and one for the columns. Clear indentation is essential so that it is obvious which statements belong to which block.
Worked examples
Example 1: MOD and DIV
State the output of print(29 DIV 4) and print(29 MOD 4).
Answer: 29 DIV 4 = 7 (4 goes into 29 seven whole times); 29 MOD 4 = 1 (the remainder).
Example 2: Writing a loop with validation
Write an algorithm that asks for a number between 1 and 10 and repeats until a valid number is entered.
num = int(input("Enter 1-10"))
while num < 1 OR num > 10
num = int(input("Invalid. Enter 1-10"))
endwhile
print("Thank you")
Example 3: SQL
Write an SQL statement to return the names of all students in Year 10 from the table Students.
SELECT Name
FROM Students
WHERE Year = 10
Example 4: Function
Write a function that takes a mark out of 80 and returns the percentage.
function percentage(mark)
return mark / 80 * 100
endfunction
Common mistakes and how to avoid them
- Forgetting to cast input.
input()returns a string; useint()before calculating. - Using
=for comparison. Use==to compare and=to assign. - Off-by-one errors with arrays. Indexes start at 0; a 5-element array runs from 0 to 4.
- Confusing functions and procedures. Only functions return a value.
- Writing a
whileloop whose condition never changes, causing an infinite loop. - Mixing up MOD and DIV.
Exam technique for "Programming Techniques"
- Use meaningful variable names and indentation so your logic is clear.
- When completing code, read the surrounding lines to keep variable names consistent.
- Choose the right loop:
forwhen the count is known,whilewhen it depends on a condition. - In SQL questions, always include
SELECT,FROMand (if needed)WHERE. - Trace your own code with a test value before moving on.
Quick revision summary
- Variables change; constants do not; assignment uses
=. - Operators include
MOD(remainder),DIV(whole division) and^(power); comparisons use==and!=. - Constructs: sequence, selection (if, switch), iteration (for, while, do…until).
- Data types: integer, real, Boolean, character, string; cast with
int(),str(),float(). - Strings: length, upper/lower, substring, left/right, concatenation, ASC/CHR.
- Files: open, readLine/writeLine, close.
- SQL:
SELECT … FROM … WHERE. - Arrays: fixed size, index from 0; 2D arrays use two indexes.
- Functions return values; procedures do not; prefer local variables.