Skip to content

2.1.2 Designing, creating and refining algorithms

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

Questions

2.1.2 Designing, creating and refining algorithms

An algorithm is a set of steps that solves a problem. Before you write a program you plan it. After you write it you test it and make it better. This topic covers how to plan an algorithm, how to show it, how to find mistakes in it and how to follow it by hand. All code is in the OCR Exam Reference Language.

Inputs, processes and outputs

Definition
An input is data that goes into a program. A process is something the program does with data. An output is the result the program gives back.

Every program can be split into these three parts. Ask yourself three questions: what does the user give the program, what does the program do with it, and what comes out?

PartExample: a program that works out the area of a rectangle
InputsThe length and the width
ProcessMultiply the length by the width
OutputThe area, shown on screen

Spotting the inputs, processes and outputs first makes the rest of the design easier. You know which variables you need and what the program must print at the end.

Structure diagrams

Definition
A structure diagram breaks a big problem into smaller sub-problems. Each sub-problem can be broken down again until every box is small enough to write as a short piece of code.

A structure diagram is drawn as boxes in a tree. The whole problem is at the top, and each level below it is more detailed. You can show the same thing as an indented list. This list describes a diagram for a quiz game.

* Quiz game
* Set up
* Load the questions
* Enter the player name
* Play a round
* Ask a question
* Check the answer
* Update the score
* Finish
* Show the score

The top box is the whole program. The three boxes under it are the main sub-problems. The boxes at the bottom are small jobs. Each small job can become a sub program.

Key Point
A structure diagram shows what the parts of a program are and how they fit together. It does not show the order of the steps or the decisions. It helps you plan, and each part can be written and tested by a different person.

Ways to show an algorithm

You can write an algorithm in plain steps, as pseudocode, as a flowchart or in the reference language.

Pseudocode

Definition
Pseudocode is a way of writing an algorithm that looks like code but does not follow the strict rules of any one language. It is used to plan.

Pseudocode has no fixed rules, so two people may write it differently. That is fine for planning. It is not accepted when a question asks you to write or refine an algorithm. In that case you must use the reference language or a high-level language.

The reference language

The reference language is the style used for every program printed in the exam. These are the main points.

* Keywords are lower case: if, then, else, elseif, endif, while, endwhile, for, next, procedure, function.
* Use == to compare and = to assign.
* A for loop includes its last value. for i = 0 to 9 runs ten times.
* Comments start with //.
* Arrays start at index 0.

pseudocode
// ask for a number and say if it is big
number = int(input("Enter a number"))
if number > 10 then
    print("Big")
else
    print("Small")
endif

Flowcharts

Definition
A flowchart is a diagram that shows the steps of an algorithm using shapes joined by arrows.

You need to know six parts of a flowchart.

SymbolShapeUse
TerminalA rounded oval (like a running track)Start or end of the algorithm
Input/outputA parallelogram (a slanted rectangle)Taking in data or showing a result
ProcessA plain rectangleA calculation or an assignment, such as total = total + 1
DecisionA diamond with two arrows leaving it, labelled Yes and NoA question that has a true or false answer
Sub programA rectangle with an extra vertical line inside each of its two sidesA call to a procedure or function
LineAn arrowShows the direction of flow from one symbol to the next

Here is a flowchart in words. Start (terminal) goes to Input number (parallelogram), then to the decision "number > 10?" (diamond). The Yes arrow goes to Output "Big" (parallelogram). The No arrow goes to Output "Small" (parallelogram). Both arrows then join and go to End (terminal). It does the same job as the program above.

A loop in a flowchart is made by an arrow that goes back up to an earlier symbol. The decision diamond decides whether the loop goes round again or leaves.

Exam Tip
Use the right shape for the job. A question is always a diamond with Yes and No arrows. Do not put a question in a rectangle. Every flowchart starts and ends with a terminal.

Errors

Definition
A syntax error is a mistake in the rules of the language, so the program will not run. A logic error is a mistake in the design, so the program runs but gives the wrong result.
TypeWhat happensExample
Syntax errorThe program stops or will not startif x > 5 with the word then missing
Logic errorThe program runs but the output is wrongUsing > when it should be >=

Syntax errors

Typical syntax errors are a missing then, endif, endwhile or next i, a misspelt keyword, using = when you need ==, and brackets that do not match. The fix is to correct the line so it follows the rules.

pseudocode
// syntax error: then is missing
if score >= 50
    print("Pass")
endif

Fixed: add then at the end of the if line.

Logic errors

The program runs, so there is no warning. You find a logic error by testing and by tracing. Typical causes are the wrong operator, a loop that runs one time too many or too few, a missing bracket in a calculation, or the wrong variable.

pseudocode
a = 4
b = 5
c = 6
average = a + b + c / 3
print(average)

This prints 11, not 5. The division happens first, so c / 3 is 2. The fix is to add brackets: average = (a + b + c) / 3.

Warning
A program with no syntax errors can still be wrong. If a program runs and gives the wrong answer, look for a logic error. Compare the output with the answer you expected and trace the code to find the line where it goes wrong.

Trace tables

Definition
A trace table is a table used to follow an algorithm by hand. It has a column for each variable and for the output. You write a new value each time a variable changes.

A trace table helps you find logic errors, work out what an algorithm does and check that it is correct. Follow the program one line at a time and do not skip a pass of a loop.

Worked example: a for loop

pseudocode
total = 0
for i = 1 to 4
    n = i * 2
    total = total + n
next i
print(total)
intotalOutput
0
122
246
3612
4820
20

The loop runs for i = 1, 2, 3 and 4, and then the program prints 20.

Worked example: a while loop

pseudocode
x = 20
count = 0
while x > 3
    x = x DIV 2
    count = count + 1
endwhile
print(count)
xcountx > 3Output
200True
101True
52True
23False
3

DIV gives the whole number part of a division, so 5 DIV 2 is 2. When x is 2 the test is false, so the loop stops. The program prints 3.

Exam Tip
In a trace table, write a value in a new row each time it changes. Check the loop condition every time before you go round again. Write the output only when a print line runs.

Nesting selection and iteration

Definition
Nesting means putting one structure inside another. You can put a selection (if) inside a loop, a loop inside a selection or one loop inside another.

The inner structure is indented so you can see where it starts and ends. The inner loop runs completely for each pass of the outer loop.

Worked example: a selection inside two loops

pseudocode
for row = 1 to 3
    for col = 1 to 2
        if (row + col) MOD 2 == 0 then
            print("X")
        else
            print("O")
        endif
    next col
next row
rowcolrow + colOutput
112X
123O
213O
224X
314X
325O

MOD gives the remainder after division. An even total has a remainder of 0 when divided by 2, so it gives X. The outer loop runs 3 times and the inner loop runs 2 times for each of those, so there are 6 outputs: X, O, O, X, X, O.

Remember
Match every opening line with its ending. if goes with endif, while with endwhile, for with next. With nested structures the inner one must finish before the outer one does.

Refining an algorithm

To refine an algorithm means to make it better after the first version. You might fix errors, make it shorter, make it easier to read or make it do fewer steps. For example, a row of separate if statements can often be replaced with if, elseif and else.

pseudocode
// first version: three tests every time
if mark >= 70 then
    print("Distinction")
endif
if mark >= 50 AND mark < 70 then
    print("Merit")
endif
if mark < 50 then
    print("Pass")
endif
pseudocode
// refined version
if mark >= 70 then
    print("Distinction")
elseif mark >= 50 then
    print("Merit")
else
    print("Pass")
endif

The refined version gives the same outputs. It is shorter, easier to read and does not repeat tests.

Writing and completing an algorithm

Follow these steps when you write an algorithm for a question.

  • 1.
    Underline the inputs and the outputs.
  • 2.
    Decide if you need a loop (count-controlled if you know how many times, condition-controlled if not) and if you need selection.
  • 3.
    Write the code in the reference language.
  • 4.
    Trace it with a small test value to check it.

Exam technique

* State or identify: one short answer, such as the name of a flowchart symbol or the line with an error.
* Describe: say what the algorithm does overall, or what a structure diagram shows.
* Explain: give a reason, such as why a logic error does not stop the program.
* Complete a trace table: write each change on a new row, follow every pass of a loop and put the output in the output column.
* Correct an algorithm: give the line number and the corrected line.
* Write, complete or refine an algorithm: use the reference language or a high-level language. Plain English and bullet points earn no marks. Check that you have then, endif, endwhile and next i, and that loops stop at the right value.