Algorithms, Flowcharts and Pseudocode
Reading and writing algorithms in the two forms Edexcel uses, the exact pseudocode command set the papers are written in, and how to trace a program without guessing.
What an algorithm is, and what it is not
An algorithm is a precise sequence of steps that solves a problem or completes a task. Two things make it precise: every step must be unambiguous, and the algorithm must always finish.
An algorithm is not a program. A program is an algorithm written in a particular programming language so a computer can run it. The same algorithm can be written as a flowchart, as pseudocode or as Python, and it is still the same algorithm. This distinction earns marks: an exam question that asks you to "write an algorithm" is not asking for perfect Python syntax, it is asking for correct logic.
The three things every algorithm needs
- Input: the data it starts with.
- Processing: what it does to that data.
- Output: what it produces.
If you can name the input, the processing and the output before you write a line, the algorithm is usually half written already.
An algorithm can be correct and still be poor. Two algorithms that both produce the right answer can differ enormously in how many steps they take, and Edexcel asks you to compare them on exactly that basis.
Flowcharts
A flowchart shows an algorithm as a diagram. Edexcel uses a fixed set of symbols and you are expected to draw them correctly, not approximately.
| Symbol | Shape | Used for |
|---|---|---|
| Terminal | Rounded rectangle | START and STOP, one at each end |
| Process | Rectangle | A calculation or an assignment, such as total = total + price |
| Input or output | Parallelogram | Reading data in or sending data out |
| Decision | Diamond | A question with exactly two labelled outputs, Yes and No |
| Subprogram | Rectangle with a double line at each side | A call to a separate named routine |
| Flow line | Arrow | The direction the algorithm moves in |
Rules that catch people out
- A decision diamond must contain a question or a condition, never a statement.
count > 10is fine,add one to countis not. - Both branches out of a decision must be labelled Yes and No, or True and False. An unlabelled branch is not a mark.
- Every arrow must point somewhere. A loop is drawn as an arrow going back up to a point above the decision.
- There is one START and normally one STOP.
A worked flowchart, described in words
An algorithm that keeps asking for a password until it is correct looks like this: START, then an input parallelogram reading the password, then a decision diamond asking password = "letmein". The No branch runs back up to just above the input, so the user is asked again. The Yes branch goes to an output parallelogram saying "Access granted" and then to STOP.
Notice where the arrow returns to. If it returned to a point below the input the program would loop forever comparing the same wrong password. Where a loop arrow rejoins the flow is the most common place to lose a mark in a flowchart question.
- 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.
The Edexcel pseudocode command set
Edexcel writes the algorithms in its papers in a specific pseudocode. You do not have to answer in it, but you absolutely have to be able to read it, and writing in it makes your intent unmistakable. It is not the same as the pseudocode other boards use, so material written for OCR or AQA will mislead you here.
Assignment, input and output
SET total TO 0
SET name TO 'Asma'
CONST VAT_RATE = 0.2
SEND 'Enter your age' TO DISPLAY
RECEIVE age FROM (INTEGER) KEYBOARD
SEND 'Hello ' & name TO DISPLAYThree points to notice. Assignment is SET ... TO, not an equals sign. Input states the type it expects, so (INTEGER) KEYBOARD reads a whole number and (STRING) KEYBOARD reads text. The & symbol joins values together, so 'Hello ' & name produces Hello Asma.
Selection
IF score >= 70 THEN
SEND 'Distinction' TO DISPLAY
ELSE IF score >= 50 THEN
SEND 'Pass' TO DISPLAY
ELSE
SEND 'Fail' TO DISPLAY
END IFThe closing keyword is END IF, two words. Conditions use = for comparison and <> for not equal.
Iteration
WHILE attempts < 3 DO
RECEIVE guess FROM (INTEGER) KEYBOARD
SET attempts TO attempts + 1
END WHILE
REPEAT
RECEIVE answer FROM (STRING) KEYBOARD
UNTIL answer = 'yes'
FOR index FROM 0 TO 9 DO
SEND index TO DISPLAY
END FOR
FOREACH mark FROM marks DO
SET total TO total + mark
END FOREACHWHILE tests the condition before the loop body, so it can run zero times. REPEAT ... UNTIL tests after the body, so it always runs at least once. FOR is count controlled, and FOREACH walks through every element of a data structure without you handling an index at all.
Data structures and subprograms
SET scores TO [12, 7, 19, 3]
SEND scores[0] TO DISPLAY # indices start at 0, so this sends 12
FUNCTION doubleIt(number)
RETURN number * 2
END FUNCTION
PROCEDURE greet(name)
SEND 'Hello ' & name TO DISPLAY
END PROCEDUREA function returns a value with RETURN. A procedure does a job but returns nothing. Indices start at zero, exactly as they do in Python, so scores[3] is the last element of a four element list.
endif, endwhile, print, input and x = 5 are OCR reference language, not Edexcel. In an Edexcel answer write END IF, END WHILE, SEND ... TO DISPLAY, RECEIVE ... FROM (TYPE) KEYBOARD and SET x TO 5.
Trace tables
A trace table records the value of every variable after each step of an algorithm. It is how you work out what a program actually does rather than what you assume it does, and Edexcel asks for one regularly.
How to do it without going wrong
- Draw one column per variable, plus a column for any output.
- Write the starting value of every variable in the first row.
- Work through the algorithm one line at a time, in the order the computer would.
- Write a new row every time a value changes. Never overwrite a value, because the history is the point.
- Test every condition literally, using the values currently in the table, not the values you expect.
Worked example
SET total TO 0
SET count TO 1
WHILE count <= 4 DO
SET total TO total + count
SET count TO count + 1
END WHILE
SEND total TO DISPLAY| Line | total | count | Condition count <= 4 | Output |
|---|---|---|---|---|
| Start | 0 | 1 | ||
| Loop 1 | 1 | 2 | True | |
| Loop 2 | 3 | 3 | True | |
| Loop 3 | 6 | 4 | True | |
| Loop 4 | 10 | 5 | True | |
| Test | 10 | 5 | False, loop ends | |
| Send | 10 | 5 | 10 |
The algorithm adds 1 + 2 + 3 + 4 and outputs 10. Notice that the loop ran four times even though count finishes on 5, because the final test is what stops it.
If you write only the final answer and it is wrong you get nothing. If you show every row and make one slip, the rest of the working can still earn marks. Always fill the table in.
Amending an algorithm
Questions often give you a working algorithm and ask you to change it, for example to also count how many numbers were entered or to reject negative values. Three habits keep this reliable:
- Declare and initialise any new variable before the loop, not inside it, or it resets every pass.
- Put the new statement in the right place: inside the loop if it happens every time, after the loop if it happens once at the end.
- Trace your amended version on a small example before you move on. It takes ninety seconds and it catches nearly every error.
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.
Key terms you must be able to define
- Algorithm
- A precise sequence of unambiguous steps that solves a problem or completes a task and always terminates.
- Flowchart
- A diagram that represents an algorithm using standard symbols joined by arrows showing the flow of control.
- Pseudocode
- A structured, language independent way of writing an algorithm using set keywords, designed to be read by people rather than run by a computer.
- Trace table
- A table used to record the value of each variable after every step of an algorithm so its behaviour can be checked by hand.
- Variable
- A named location in memory whose value can change while the program is running.
- Constant
- A named value that is set once and cannot be changed while the program is running.
- Selection
- A construct that chooses between different sets of instructions based on whether a condition is true.
- Iteration
- A construct that repeats a set of instructions, either a fixed number of times or while a condition holds.
- Decision symbol
- The diamond in a flowchart that contains a condition and has two labelled outputs, one for true and one for false.
- Terminal symbol
- The rounded rectangle used for START and STOP at each end of a flowchart.
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
This topic is marked on precision, and precision is a habit rather than a talent.
Trace literally. The commonest reason a grade 7 student drops these marks is deciding what a loop "obviously" does instead of evaluating the condition with the values actually in the table. Write the condition out, write True or False next to it, then move.
Use the right dialect. Writing endwhile in an Edexcel answer will usually still be accepted, because the mark scheme rewards correct logic, but reading the paper is harder if the command set is unfamiliar. Learn SET ... TO, SEND ... TO DISPLAY and RECEIVE ... FROM (TYPE) KEYBOARD until they are automatic.
Know why one loop rather than another. A WHILE loop can execute zero times and a REPEAT ... UNTIL loop always executes at least once. Menu systems and password prompts use REPEAT because the question has to be asked before it can be answered.
Draw flowcharts with the right shapes. A diamond that contains a statement instead of a condition, or a branch with no Yes or No label, loses the mark even when the logic is right.
- Be able to write a trace table for a nested loop without hesitating
- Be able to name every flowchart symbol and what it is used for
- Be able to convert a flowchart into Edexcel pseudocode and back again
- Be able to explain when a WHILE loop is right and when a REPEAT loop is right
- Be able to amend a given algorithm by adding a counter, a total or a validation check
Mistakes that cost marks here
- Putting a statement such as 'add one to count' inside a decision diamond. A diamond holds a condition with two possible answers.
- Drawing a loop arrow that rejoins the flow below the input, so the same value is tested forever.
- Overwriting values in a trace table instead of adding a new row, which destroys the working the marks are for.
- Forgetting that indices start at zero, so treating scores[1] as the first element of a list.
- Initialising a total or counter inside the loop, so it resets on every pass and the final answer is always wrong.
- Confusing WHILE and REPEAT UNTIL. WHILE tests first and may run zero times, REPEAT tests last and always runs once.
The word algorithm comes from al-Khwarizmi, a mathematician working in Baghdad around the year 820. When his book on Indian numerals was translated into Latin, his name became algorismus, and for centuries that word simply meant doing arithmetic with the digits 0 to 9 instead of Roman numerals.
Knowledge check
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 WHILE loop tests its condition before the body runs and a REPEAT loop tests it afterwards
- LA WHILE loop may run zero times, a REPEAT loop always runs at least once
A WHILE loop tests its condition before the body is executed, whereas a REPEAT UNTIL loop executes the body first and tests the condition afterwards. As a result, the body of a WHILE loop may never run at all if the condition is false to begin with, while the body of a REPEAT UNTIL loop always runs at least once.
- LIt records the value of each variable at each step of the algorithm
- LThe programmer can compare the actual values with the values expected
- LThe step at which a value first becomes wrong identifies where the error is
A trace table records the value held by every variable after each step of an algorithm, together with anything the algorithm outputs. Working through the algorithm by hand and filling the table in lets the programmer compare the values the program actually produces with the values it should be producing at that point. The first row where a value differs from what was expected shows exactly which instruction is at fault, which is what makes a trace table so effective at locating logic errors, since a logic error produces a wrong answer without producing any error message at all.
- LA decision is shown as a diamond containing a condition with two labelled outputs
- LInput and output use a parallelogram and a process uses a rectangle
- LThe flowchart begins and ends with a terminal symbol and every step is joined by arrows showing the flow
A flowchart must begin and end with a terminal symbol, a rounded rectangle containing START or STOP, so that it is clear where the algorithm starts and finishes. Each type of step must use the correct shape: a rectangle for a process such as a calculation, a parallelogram for input or output, and a diamond for a decision. A decision must contain a condition rather than an instruction and must have exactly two outputs, each labelled Yes or No, and every symbol must be connected by arrows that show the direction the algorithm flows in, with any loop drawn as an arrow returning to a point earlier in the sequence.
- LA total is initialised to zero before the loop
- LA loop that repeats exactly ten times
- LA number is input from the user inside the loop
- LThe number is added to the running total inside the loop
- LThe total is output after the loop has finished
SET total TO 0, then FOR count FROM 1 TO 10 DO, and inside that loop SEND 'Enter a number' TO DISPLAY, RECEIVE number FROM (INTEGER) KEYBOARD and SET total TO total + number, then END FOR, and finally SEND total TO DISPLAY. The total must be set to zero before the loop begins so that it is not reset on each pass, the input and the addition both sit inside the loop so that they happen ten times, and the output sits after END FOR so that the total is displayed once, when all ten numbers have been added.
- LPseudocode is not tied to any one programming language
- LThe programmer can concentrate on the logic without worrying about syntax
- LIt is easier for other people, including non programmers, to read and check
- LErrors in the design can be found and corrected before time is spent coding
Pseudocode is deliberately not tied to any particular programming language, so the programmer can set out the logic of the solution without having to be correct about the syntax of Python at the same time. That separation matters because it means the design can be judged on whether the steps are right, rather than on whether a colon or a bracket is missing. Pseudocode is also far easier for other people to read, including team members who work in a different language and clients who do not program at all, so the design can be reviewed and agreed before any code exists. Finding a flaw in the logic at that stage costs a few minutes, whereas finding the same flaw after the program has been written, tested and documented costs a great deal more.