KS41CP2 1.2 34 min read 10 question quiz 17 exam marks

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.

Correct versus efficient

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.

SymbolShapeUsed for
TerminalRounded rectangleSTART and STOP, one at each end
ProcessRectangleA calculation or an assignment, such as total = total + price
Input or outputParallelogramReading data in or sending data out
DecisionDiamondA question with exactly two labelled outputs, Yes and No
SubprogramRectangle with a double line at each sideA call to a separate named routine
Flow lineArrowThe direction the algorithm moves in

Rules that catch people out

  • A decision diamond must contain a question or a condition, never a statement. count > 10 is fine, add one to count is 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.

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.

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

PSEUDOCODE
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 DISPLAY

Three 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

PSEUDOCODE
IF score >= 70 THEN
    SEND 'Distinction' TO DISPLAY
ELSE IF score >= 50 THEN
    SEND 'Pass' TO DISPLAY
ELSE
    SEND 'Fail' TO DISPLAY
END IF

The closing keyword is END IF, two words. Conditions use = for comparison and <> for not equal.

Iteration

PSEUDOCODE
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 FOREACH

WHILE 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

PSEUDOCODE
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 PROCEDURE

A 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.

Do not import OCR habits

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

  1. Draw one column per variable, plus a column for any output.
  2. Write the starting value of every variable in the first row.
  3. Work through the algorithm one line at a time, in the order the computer would.
  4. Write a new row every time a value changes. Never overwrite a value, because the history is the point.
  5. Test every condition literally, using the values currently in the table, not the values you expect.

Worked example

PSEUDOCODE
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
LinetotalcountCondition count <= 4Output
Start01
Loop 112True
Loop 233True
Loop 364True
Loop 4105True
Test105False, loop ends
Send10510

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.

Trace tables are marked on the rows, not the answer

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.

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.

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.

DefineAlgorithm
AnswerA precise sequence of unambiguous steps that solves a problem or completes a task and always terminates.
DefineFlowchart
AnswerA diagram that represents an algorithm using standard symbols joined by arrows showing the flow of control.
DefinePseudocode
AnswerA structured, language independent way of writing an algorithm using set keywords, designed to be read by people rather than run by a computer.
DefineTrace table
AnswerA table used to record the value of each variable after every step of an algorithm so its behaviour can be checked by hand.
DefineVariable
AnswerA named location in memory whose value can change while the program is running.
DefineConstant
AnswerA named value that is set once and cannot be changed while the program is running.
DefineSelection
AnswerA construct that chooses between different sets of instructions based on whether a condition is true.
DefineIteration
AnswerA construct that repeats a set of instructions, either a fixed number of times or while a condition holds.

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

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

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

0 of 10 answered
1In the Edexcel pseudocode command set, how is a value assigned to a variable?
2Which flowchart symbol is used for a decision?
3What does RECEIVE age FROM (INTEGER) KEYBOARD do?
4Which loop always executes its body at least once?
5A trace table is used to:
6What is output by this algorithm? SET x TO 5, WHILE x > 8 DO, SEND x TO DISPLAY, SET x TO x + 1, END WHILE
7In Edexcel pseudocode, what does the symbol & do in SEND 'Total: ' & total TO DISPLAY?
8Which element of a flowchart is drawn as a parallelogram?
9A program must ask a user for a menu choice and keep asking until the choice is valid. Which construct fits best?
10Why is an algorithm not the same thing as a program?
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.

17 marks
1State two differences between a WHILE loop and a REPEAT UNTIL loop.2 marks
State

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

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
2Describe the purpose of a trace table and explain how it helps a programmer find a logic error.3 marks
Describe

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

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
3Describe three rules that must be followed when drawing a flowchart.3 marks
Describe

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

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.

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 or a flowchart, that asks the user for ten numbers, adds them up and outputs the total.5 marks
Write

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

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.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.
5Explain why an algorithm might be written as pseudocode before it is written as a program in Python.4 marks
Explain

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

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.

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