Designing, Creating and Refining Algorithms
Pseudocode, flowcharts, trace tables and finding errors in someone else's algorithm, which is the skill Paper 2 tests most heavily.
Flowcharts
A flowchart is a diagram showing an algorithm as a series of connected symbols.
| Symbol | Shape | Meaning |
|---|---|---|
| Terminal | Rounded rectangle | Start or stop |
| Process | Rectangle | A calculation or assignment |
| Input or output | Parallelogram | Reading input or displaying output |
| Decision | Diamond | A question with yes and no branches |
| Sub program | Rectangle with double side bars | A call to a subroutine |
| Flow line | Arrow | The direction of flow |
Reading a flowchart
The rule is simple: follow the arrows. At a diamond there are always exactly two ways out, one for yes and one for no, and they must be labelled.
A loop appears as an arrow that goes back to an earlier point in the diagram.
An unlabelled diamond is ambiguous, and in the exam it loses the mark.
- Each shape has one meaning: terminals start and stop, parallelograms are input or output, rectangles are processes, diamonds are decisions.
- Flow lines show the order, and every chart starts and stops with a terminal.
- A decision has two exits, labelled Yes and No, and the two routes join up again.
- The flowchart: ovals for start and end, slanted boxes for input and output, a diamond for a decision with a yes branch and a no branch.
- The Python version has the same steps, matched by colour.
- The pseudocode is the same algorithm again. Only the notation changes.
Pseudocode and the OCR reference language
Pseudocode describes an algorithm in structured English, without the strict syntax of a real language. OCR provides its own reference language, and you should use it in written answers because the mark schemes are written around it.
The core constructs
// Variables and assignment
name = "Sam"
score = 0
global highScore = 0
// Input and output
name = input("What is your name?")
print("Hello " + name)
// Selection
if score > 50 then
print("Pass")
elseif score = 50 then
print("Borderline")
else
print("Fail")
endif
// Case selection
switch grade:
case "A":
print("Excellent")
case "B":
print("Good")
default:
print("See teacher")
endswitch
// Count controlled loop
for i = 0 to 9
print(i)
next i
// Condition controlled loops
while answer != "quit"
answer = input("Enter a command")
endwhile
do
guess = input("Guess the number")
until guess == 7Subroutines
function addTax(amount)
return amount * 1.2
endfunction
procedure greet(name)
print("Hello " + name)
endprocedure
total = addTax(100)
greet("Sam")A function returns a value. A procedure does not. This distinction is examined regularly.
Arrays and strings
array scores[5]
scores[0] = 42
print(scores[0])
array board[3,3] // 2D array
board[1,2] = "X"
name = "Computer"
print(name.length) // 8
print(name.substring(0,4)) // Comp
print(name.upper) // COMPUTERAn array declared with 5 elements has indexes 0, 1, 2, 3 and 4. There is no index 5. This is the single most common source of errors in exam answers.
File handling
myFile = open("scores.txt")
line = myFile.readLine()
myFile.writeLine("New score")
myFile.close()Trace tables
A trace table records the value of every variable after each step of an algorithm. It is how you work out what an algorithm actually does, rather than what you assume it does.
How to complete one
- Draw a column for every variable and one for any output.
- Work through the algorithm one line at a time.
- Write a new row every time a value changes.
- Do not skip iterations of a loop. Errors hide in the second and third pass.
Worked example
total = 0
for i = 1 to 4
total = total + i
if total > 5 then
print(total)
endif
next i| i | total | Output |
|---|---|---|
| 1 | 1 | |
| 2 | 3 | |
| 3 | 6 | 6 |
| 4 | 10 | 10 |
Fill in every row even if you can see the answer. A correct final value with an empty table often scores less than a complete table with one arithmetic slip.
Trace table trainer
Fill in a trace table row by row and have it marked as you type. This tool needs JavaScript, so turn it on to use it. Everything you need to answer the exam question is explained in the text above.
- Run the program by hand, one line at a time. Line 3 is the one that repeats.
- Follow four rules: one line at a time, one column per variable, a new row for each change, and check the last row.
- Each time the loop runs, i goes up by one and total grows: 0, 1, 3, 6.
- The output is written when print runs. Here it is 6.
Finding and correcting errors
Paper 2 regularly gives you an algorithm containing deliberate errors and asks you to find and fix them. Work through this checklist.
The checklist
- Off by one in loops.
for i = 1 to 10runs ten times starting at 1.for i = 0 to 10runs eleven times. Check against what the question requires. - Array index out of range. An array of size n has indexes 0 to n-1.
- Assignment against comparison.
=assigns in most pseudocode,==compares. In OCR reference language both are used, so read carefully. - Wrong comparison operator.
>instead of>=changes behaviour exactly at the boundary, which is where exam questions target. - Variable used before it is initialised, for example adding to a total that was never set to 0.
- Infinite loop, where the condition can never become false because the variable inside the loop is never changed.
- Wrong data type, for example comparing the string "5" with the integer 5.
- Logic in the wrong order, such as printing the average before calculating it.
Refining an algorithm
Making an algorithm more efficient or more robust:
- Replace repeated code with a loop or a subroutine
- Stop searching as soon as the item is found rather than checking the whole list
- Validate input before it is used, rather than letting the program crash
- Remove calculations from inside a loop when the value never changes
- Use a more efficient algorithm, for example binary search instead of linear search on sorted data
A more efficient algorithm produces the same output using fewer operations, less memory, or both. Say which of the two you have improved.
Key terms you must be able to define
- Algorithm
- A sequence of unambiguous, ordered steps that solves a problem or completes a task.
- Pseudocode
- A structured description of an algorithm in English-like statements, independent of any programming language.
- Flowchart
- A diagram representing an algorithm using standard symbols connected by arrows.
- Trace table
- A table recording the value of each variable after every step of an algorithm.
- Function
- A subroutine that returns a value to the code that called it.
- Procedure
- A subroutine that carries out a task but does not return a value.
- Efficiency
- How well an algorithm uses resources, usually measured in the number of steps or the memory required.
- Off by one error
- A mistake where a loop runs one time too many or too few, or an array index is one out.
Flashcards
Say the definition out loud before you flip the card. Retrieving it from memory is what builds recall, reading it again is not.
Reach the top grade on this topic
Paper 2 is dominated by this topic, and the difference between grades is almost entirely discipline.
Fill in the whole trace table. Every row, every iteration. Method marks are real marks.
Use OCR reference language, not Python, in written answers. Both are accepted, but the mark schemes are written in reference language, so matching it removes any chance of ambiguity. Whichever you choose, be consistent within one answer.
When correcting an error, say three things: where it is, what is wrong, and what it should be. "Line 4 uses > but should use >=, because a score of exactly 50 should count as a pass."
Check boundaries automatically. If a condition involves a number, ask what happens when the value is exactly that number. That is where the examiner has put the error.
- Complete a trace table for a nested loop without losing track
- Convert a flowchart into pseudocode and back
- Write a function and a procedure correctly and explain the difference
- Find three deliberate errors in a twelve line algorithm in under five minutes
Mistakes that cost marks here
- Leaving a trace table half filled because you spotted the answer early.
- Assuming arrays start at 1. In OCR reference language, and in Python, they start at 0.
- Forgetting that a for loop from 1 to 5 includes 5, so it runs five times.
- Writing a function that prints instead of returning, or a procedure with a return statement.
- Not labelling the yes and no branches of a decision diamond in a flowchart.
- Correcting an error without saying which line it is on.
Flowchart symbols were standardised by ANSI in the 1960s, and the shapes have barely changed since. The diamond for a decision is so recognisable that it still appears in road signs, business diagrams and video game design documents.
Knowledge check
array scores[6]. What is the highest valid index?for i = 3 to 7 execute?if score > 50. What kind of error is this?x = 5 then x = x + 3 then print(x) would show which output?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.
- LA function returns a value to the calling code
- LA procedure carries out a task without returning a value
A function returns a value to the part of the program that called it, so its result can be assigned to a variable or used in an expression. A procedure performs a task, such as displaying a menu, but does not return any value to the calling code.
- LIdentifies that the condition selects even values of i
- LShows total updating to 2 when i is 2
- LShows total updating to 6 when i is 4
- LStates the final output is 6
The loop runs with i taking the values 1, 2, 3, 4 and 5. The condition i MOD 2 equals 0 is only true when i is even, so total is only updated on those iterations. When i is 1 the condition is false and total stays 0. When i is 2 the condition is true so total becomes 0 plus 2, which is 2. When i is 3 the condition is false and total stays 2. When i is 4 the condition is true so total becomes 2 plus 4, which is 6. When i is 5 the condition is false and total stays 6. The final output is therefore 6.
largest = 0 is used before the loop and the array contains negative numbers. Identify the error and describe how to correct it.3 marks- LThe error is initialising largest to 0
- LAll the values are negative, so none is greater than 0 and largest is never replaced
- LCorrect by initialising largest to the first element of the array
The error is that largest is initialised to 0 before the loop begins. Because every value in the array is negative, no element is ever greater than 0, so the comparison inside the loop is never true and largest is never updated, which is why 0 is always output. The correction is to initialise largest to the first element of the array, using largest = numbers[0], and then loop from the second element onwards. This guarantees that largest always holds a value that actually appears in the array, so the algorithm works correctly regardless of whether the values are positive or negative.
- LDeclares an array to hold 5 values
- LUses a count controlled loop to run 5 times
- LTakes input inside the loop and stores it in the array
- LMaintains a running total
- LDivides the total by 5 to find the average
- LOutputs the average
array numbers[5] total = 0 for i = 0 to 4 numbers[i] = input("Enter a number") total = total + numbers[i] next i average = total / 5 print("The average is " + average) The array is declared with five elements, which have indexes 0 to 4. A count controlled loop runs five times, taking a number from the user on each pass, storing it at the current index and adding it to a running total. After the loop finishes, the total is divided by 5 to give the average, which is then output.
- LEfficiency means producing the same result using fewer steps or less memory
- LFirst method such as exiting a search early when the item is found
- LSecond method such as moving a calculation outside a loop when the value does not change
- LOr using a more efficient algorithm such as binary search instead of linear search
Making an algorithm more efficient means changing it so that it produces exactly the same correct result while using fewer steps, less memory, or both. One way is to exit a loop as soon as the work is complete: a linear search that stops the moment the target value is found avoids checking every remaining element, which on average halves the number of comparisons. A second way is to move any calculation whose result does not change out of a loop and perform it once before the loop starts, since repeating an identical calculation on every iteration is wasted work. A third and often much more significant improvement is to select a fundamentally better algorithm, for example replacing a linear search with a binary search on sorted data, which reduces the number of comparisons on a list of a million items from up to a million down to about twenty.