KS4J277 2.1.2 32 min read 10 question quiz 19 exam marks

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.

SymbolShapeMeaning
TerminalRounded rectangleStart or stop
ProcessRectangleA calculation or assignment
Input or outputParallelogramReading input or displaying output
DecisionDiamondA question with yes and no branches
Sub programRectangle with double side barsA call to a subroutine
Flow lineArrowThe 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.

Every decision needs both branches labelled

An unlabelled diamond is ambiguous, and in the exam it loses the mark.

Flowchart symbols, and a worked exampleThe standard flowchart symbols on the left. A terminal, a rounded shape, marks where the program starts and stops. A parallelogram is input or output, data coming in or being shown. A rectangle is a process, a calculation or an action. A diamond is a decision: a question with two exits, Yes and No. Arrows are flow lines that show the order. On the right is a worked example. The flowchart starts, inputs an age, then asks whether age is less than 16. If yes the price is set to 5, and if no it is set to 8. Both routes join up again, the price is output, and the chart stops. The same logic is written as code in a small box beside it.The symbolsStartStart / Stopwhere it begins and endsINPUTInput / Outputdata in, or shown outx = x + 1Processa calculation or an actionx > 5 ?Decisiona question with two exitsflow line: the order1Example: a ticket priceStartINPUT ageage < 16 ?YesNoprice = 5price = 8OUTPUT priceStop23age = input()if age < 16:  price = 5else:  price = 8print(price)the same thingas code
  1. Each shape has one meaning: terminals start and stop, parallelograms are input or output, rectangles are processes, diamonds are decisions.
  2. Flow lines show the order, and every chart starts and stops with a terminal.
  3. A decision has two exits, labelled Yes and No, and the two routes join up again.
Use the right shape for the job, label every decision exit, and let every route reach the end.
One algorithm as a flowchart, as Python and as pseudocode, with matching steps in matching coloursThe same algorithm written three ways. The flowchart starts, inputs an age, then reaches a decision diamond that asks whether age is greater than or equal to 18. If yes it outputs Adult, if no it outputs Child, and both paths join and reach the end. The Python code has the same steps: age equals int of input, if age is at least 18 print Adult, else print Child. The pseudocode is the same again, ending with endif. The input is coloured blue, the decision yellow, and the two outputs green and red in all three versions, so each step can be matched across them. Rounded ovals mean start and end, slanted boxes mean input and output, and a diamond means a decision.The flowchart1Startinput ageage >= 18 ?yesnooutput "Adult"output "Child"Endage.pyage = int(input("Age? "))if age >= 18:    print("Adult")else:    print("Child")2the same, in pseudocodeage = input("Age? ")if age >= 18 then    print("Adult")else    print("Child")endif3input, outputdecisionstart, endsame colour = same step, in all three
  1. 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.
  2. The Python version has the same steps, matched by colour.
  3. The pseudocode is the same algorithm again. Only the notation changes.
A flowchart, pseudocode and a program are three ways to write one algorithm. Practise moving between them.

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

OCR reference language
// 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 == 7

Subroutines

OCR reference language
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

OCR reference language
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)               // COMPUTER
Arrays start at 0

An 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

OCR reference language
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

  1. Draw a column for every variable and one for any output.
  2. Work through the algorithm one line at a time.
  3. Write a new row every time a value changes.
  4. Do not skip iterations of a loop. Errors hide in the second and third pass.

Worked example

OCR reference language
total = 0
for i = 1 to 4
    total = total + i
    if total > 5 then
        print(total)
    endif
next i
itotalOutput
11
23
366
41010
Marks are given for the table, not just the final answer

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.

A trace table for a loop that adds 1, 2 and 3A short program sets total to 0, then loops for i from 1 to 3 adding i to total, then prints total. Beside it is its trace table, with one column for the line number, one for i, one for total and one for the output. Line 1 sets total to 0. Line 2 sets i to 1, line 3 makes total 1. Line 2 sets i to 2, line 3 makes total 3. Line 2 sets i to 3, line 3 makes total 6. Line 4 prints 6, so the output column of the last row holds 6. The method: take one line at a time, give each variable its own column and the output one too, write a new row each time a value changes, and read the answer from the last row.total.py1total = 02for i in range(1, 4):3    total = total + i4print(total)1How to trace2Take one line at a timeand do exactly what it saysOne column per variableand one for the outputWrite a new row each timea value changes, never overwriteCheck the last rowit is the answer the program givesThe trace table3lineitotaloutput10210311221323233336436646 is printed: 1 + 2 + 3
  1. Run the program by hand, one line at a time. Line 3 is the one that repeats.
  2. Follow four rules: one line at a time, one column per variable, a new row for each change, and check the last row.
  3. Each time the loop runs, i goes up by one and total grows: 0, 1, 3, 6.
  4. The output is written when print runs. Here it is 6.
A trace table shows exactly what the program does, one step at a time. It is how you find a logic error.

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

  1. Off by one in loops. for i = 1 to 10 runs ten times starting at 1. for i = 0 to 10 runs eleven times. Check against what the question requires.
  2. Array index out of range. An array of size n has indexes 0 to n-1.
  3. Assignment against comparison. = assigns in most pseudocode, == compares. In OCR reference language both are used, so read carefully.
  4. Wrong comparison operator. > instead of >= changes behaviour exactly at the boundary, which is where exam questions target.
  5. Variable used before it is initialised, for example adding to a total that was never set to 0.
  6. Infinite loop, where the condition can never become false because the variable inside the loop is never changed.
  7. Wrong data type, for example comparing the string "5" with the integer 5.
  8. 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
Efficiency means fewer steps

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.

DefineAlgorithm
AnswerA sequence of unambiguous, ordered steps that solves a problem or completes a task.
DefinePseudocode
AnswerA structured description of an algorithm in English-like statements, independent of any programming language.
DefineFlowchart
AnswerA diagram representing an algorithm using standard symbols connected by arrows.
DefineTrace table
AnswerA table recording the value of each variable after every step of an algorithm.
DefineFunction
AnswerA subroutine that returns a value to the code that called it.
DefineProcedure
AnswerA subroutine that carries out a task but does not return a value.
DefineEfficiency
AnswerHow well an algorithm uses resources, usually measured in the number of steps or the memory required.
DefineOff by one error
AnswerA mistake where a loop runs one time too many or too few, or an array index is one out.

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

Avoid these
  • 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.
Fun fact

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

0 of 10 answered
1Which flowchart symbol represents a decision?
2What is the difference between a function and a procedure?
3An array is declared as array scores[6]. What is the highest valid index?
4What is the purpose of a trace table?
5How many times does for i = 3 to 7 execute?
6Which is most likely to cause an infinite loop?
7An algorithm should award a pass for a score of 50 or more, but uses if score > 50. What kind of error is this?
8In OCR reference language, which keyword ends a count controlled loop?
9Which change would make a linear search of a list more efficient?
10A trace table for the code x = 5 then x = x + 3 then print(x) would show which output?
Score 0 / 10

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.

19 marks
1State two differences between a function and a procedure.2 marks
State

Mark scheme0 / 2
  • LA function returns a value to the calling code
  • LA procedure carries out a task without returning a value
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Complete a trace table for the following algorithm and state the final output.total = 0, then for i = 1 to 5: if i MOD 2 == 0 then total = total + i, next i, then print(total)4 marks
Complete

Mark scheme0 / 4
  • 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
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3A student writes an algorithm to find the largest number in an array of 10 values, but it always outputs 0. The line largest = 0 is used before the loop and the array contains negative numbers. Identify the error and describe how to correct it.3 marks
Identify

Mark scheme0 / 3
  • 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
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
4Write an algorithm, using pseudocode, that asks the user for 5 numbers, stores them in an array, and then outputs the average.6 marks
Write

Mark scheme0 / 6
  • 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
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Explain what is meant by making an algorithm more efficient, and give two ways an algorithm could be made more efficient.4 marks
Explain

Mark scheme0 / 4
  • 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
Model answer

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
Machine mark 0 / 19