Skip to content

0478 · Unit 7 · Paper 2: Algorithms, programming and logic

Algorithm design and problem-solving.

0478 · Unit 7 · Algorithm design and problem-solving
Revisionbyexamplicity

Program development and decomposition

§7 · Algorithm design and problem-solving

Good programs do not start with code. You work out what is needed, plan, code, then test: the four stages of the program development life cycle. Each produces what the next one uses.

The program development life cycle has four stages; each produces what the next one uses.

The four stages of development

1Analysis

Understand the problem

  • Requirements: what the program must do
  • Abstraction: leave out detail that does not matter
  • Decomposition: split the problem into smaller parts
passes onrequirements
2Design

Plan the solution

  • Structure diagram
  • Flowchart
  • Pseudocode
passes ona design
3Coding

Write the program

  • Write program code from the design
  • Iterative testing: test and correct each part as it is written
passes onprogram code
4Testing

Check the whole program

  • Run it with test data
  • Compare actual results with expected results
  • Correct the errors
resulta working program

Break a system into parts

A structure diagram shows how a system is broken down into sub-systems, and those into further sub-systems. Decomposing a problem into its inputs, processes, outputs and storage is a good start.

the systemsub-systemssmaller partsLibrary borrowing systemInputMemberIDBookIDProcessCheckmemberRecordthe loanOutputDuedateRejectionmessageStorageMemberdetailsLoanrecordsKeep splitting until each part is simple enough to solve.
Library borrowing systemInputMember IDBook IDProcessCheck memberRecord the loanOutputDue dateRejection messageStorageMember detailsLoan records

Three ways to write down a design

A design is written down before any code. You must be able to name each method, say what it shows, and read and complete one in the exam.

Structure diagram

Shows the parts: a system broken down into sub-systems, level by level (hierarchical).

Use it to decompose a problem.

Flowchart

Shows the steps of an algorithm as symbols joined by arrows: its decisions and the order they happen in.

Next page: the six symbols.

Pseudocode

Shows the steps in plain language, as structured, code-like statements.

Used on every algorithm page that follows.

Describing an algorithm

  • Purpose: say what result it makes from its inputs.
  • Processes: explain the main steps in the order they run. A list of keywords does not say what the algorithm achieves.
Your turn

1 In which stage are actual results compared with expected results?

2 Which design tool shows a system as a hierarchy of sub-systems?

3 A school canteen app takes lunch orders. Decompose it: give one input, one process, one output and one thing it stores.

  1. 1
    Testing
  2. 2
    a structure diagram
  3. 3
    for example: input a pupil ID and a meal choice; process: check the pupil has enough credit; output: an order confirmation; storage: pupil credit balances
Tick what you can do now
Practise with m26/22 Q3; s26/22 Q4; w25/21 Q5 (older paper: completing a structure diagram); w24/21 Q5 (older paper: comparing design methods)
1 / 15
0478 · Unit 7 · Algorithm design and problem-solving
Revisionbyexamplicity

Flowcharts and validation loops

§7 · Algorithm design

Before writing code, it helps to see an algorithm as a picture: where it starts, where it makes a decision, where it goes round again. A flowchart shows the steps of an algorithm and their order, using six standard symbols that everyone reads the same way.

The six symbols, in one flowchart

Follow the arrows from START. The diamond asks one question: a score outside 0 to 100 takes the Yes exit and loops back to the input, so the user is asked again.

STARTOUTPUT "Score 0–100"INPUT ScoreScore < 0ORScore > 100?YesOUTPUT "Try again"NoOUTPUT "Accepted"STOP

The six symbols

TerminatorSTART or STOPProcessan action or assignmentInput / OutputINPUT or OUTPUTDecisiona test with Yes / No exitsSubroutinecall a separate flowchartFlow linedirection of control
Label every decision exit Yes / No; put an arrow on every flow line; write a prompt before an input.

The same algorithm in pseudocode and Python

Each symbol becomes a line of code. The diamond and the arrow back up become the WHILE loop, and the output on its Yes path goes inside it.

Cambridge pseudocode
DECLARE Score : INTEGER
OUTPUT "Score 0–100"
INPUT Score
WHILE Score < 0 OR Score > 100 DO
OUTPUT "Try again"
INPUT Score
ENDWHILE
OUTPUT "Accepted"
Python
print("Score 0–100")
Score = int(input())
while Score < 0 or Score > 100:
print("Try again")
Score = int(input())
print("Accepted")
To amend a flowchart, say where the new symbol goes, what it contains and where its flow lines lead.
Your turn

1 Which flowchart symbol holds Is Age > 17?

2 Which symbol holds INPUT Name?

3 The inputs to the validation algorithm are 150, −3, 42. Write every output in order.

  1. 1
    a decision (diamond), with Yes and No exits
  2. 2
    an input/output parallelogram
  3. 3
    Score 0–100, Try again, Try again, Accepted: 150 and −3 are out of range, 42 is accepted
Tick what you can do now
Practise with s26/21 Q10(a), Q10(b); s26/23 Q5(b); w24/22 Q3(a) (older paper: symbol matching)
2 / 15
0478 · Unit 7 · Algorithm design and problem-solving
Revisionbyexamplicity

Validation and verification

§7 · Algorithm design

A program can only be as right as the data put into it. Two kinds of check protect input. One asks: is this data sensible? The other asks: was it entered without changing?

Two kinds of check

Validation

An automatic check by the program that input data is sensible and meets set rules. Unreasonable data is rejected before it is stored or processed.

Verification

A check that data has not changed or gained errors during input, so it matches the original source.

Six types of validation check

Name each check, say what it tests, and give a value it accepts and one it rejects.

CheckTests that…Example ruleAcceptsRejects
Rangea value is between a lower and an upper limitscore from 0 to 10075101−5
Lengthdata has an exact, minimum or maximum number of charactersmember code has 6 charactersLB0421AB12
Typedata is the correct data typeage is a whole number15“ten”15.5
Presencedata has been entered (not left blank)surname must be enteredPatel    blank
Formatcharacters follow a set patterntwo letters then four digitsAB12341234AB
Check digitthe final digit matches one recalculated from the other digitsISBN, barcode; the method below304752304572 swapped

A specified check-digit method

This method uses weights 1, 2, 3, 4, 5 and the remainder on division by 11.

Digits 3 0 4 7 5:
3 × 1 + 0 × 2 + 4 × 3 + 7 × 4 + 5 × 5 = 68 → MOD(68, 11) = 2 → the code is stored as 304752
digitsweightproduct3× 130× 204× 3127× 4285× 5252checkdigit3 + 0 + 12 + 28 + 25 = 68 → MOD(68, 11) = 2
  1. 1
    The code is stored as 304752.
  2. 2
    When it is typed in again, the program works out the last digit again from the first five.
  3. 3
    If 7 and 5 are swapped (304572), it gets 4, not 2, so the code is rejected.

Two types of verification check

Name each one and describe how it is carried out.

Visual check

The user compares the data on screen with the original document and corrects any differences.

Double entry

The data is entered twice; the two entries are compared and accepted only if they match, e.g. a new password.

An entered age of 25 can pass a range check and a double-entry check even if the person is really 26: neither check can prove the data is true, only that it is sensible or has not changed on input.
Your turn

1 A phone number must have exactly 11 characters. Which validation check is this?

2 A user types a new email address twice and the two are compared. Validation or verification? Which check?

3 Use the page's check-digit method on the digits 2 1 3 0 4. What code is stored?

  1. 1
    a length check
  2. 2
    verification, by double entry
  3. 3
    2 × 1 + 1 × 2 + 3 × 3 + 0 × 4 + 4 × 5 = 33; MOD(33, 11) = 0, so the code is stored as 213040
Tick what you can do now
Practise with m26/22 Q1, Q2(b); s26/22 Q3(a)(i), Q3(a)(ii), Q3(b); s26/23 Q3(b); m25/22 Q4(a) (older paper: distinguishing validation and verification)
3 / 15
0478 · Unit 7 · Algorithm design and problem-solving
Revisionbyexamplicity

Writing validation checks

§7 · Algorithm design

A program cannot stop someone typing nonsense, but it can refuse to carry on until the input makes sense. Each check uses a REPEAT … UNTIL loop: input at least once, then again until it passes.

Four checks, each written as a loop

All four loops have the same shape; only the test changes. Under each one, Run it tries two inputs: the amber one gets the error message, the green one ends the loop.

Length check
DECLARE Code : STRING
REPEAT
OUTPUT "Enter a 6-character code"
INPUT Code
IF LENGTH(Code) <> 6
THEN
OUTPUT "Must be 6 characters"
ENDIF
UNTIL LENGTH(Code) = 6
Run itAB12“Must be 6 characters”, asked againAB1234accepted: the loop ends
Presence check
DECLARE Surname : STRING
REPEAT
OUTPUT "Enter your surname"
INPUT Surname
IF Surname = ""
THEN
OUTPUT "Surname must not be blank"
ENDIF
UNTIL Surname <> ""
Run it (blank) “Surname must not be blank”, asked againPatelaccepted: the loop ends
Type check · whole number
DECLARE Age : REAL
REPEAT
OUTPUT "Enter your age"
INPUT Age
IF ROUND(Age, 0) <> Age
THEN
OUTPUT "Enter a whole number"
ENDIF
UNTIL ROUND(Age, 0) = Age
Run it15.5“Enter a whole number”, asked again15accepted: the loop ends
Format check · starts with PD
DECLARE Code : STRING
REPEAT
OUTPUT "Enter the product code"
INPUT Code
IF SUBSTRING(Code, 1, 2) <> "PD"
THEN
OUTPUT "Code must start with PD"
ENDIF
UNTIL SUBSTRING(Code, 1, 2) = "PD"
Run itXY1234“Code must start with PD”, asked againPD1234accepted: the loop ends

Write the condition for a range check

A range has two limits, so its condition needs two comparisons, and how you join them decides what the loop accepts.

Range check

Use a condition with both limits:

UNTIL Mark >= 0 AND Mark <= 100
  • To accept a value in range, both comparisons must be true: join them with AND.
  • To reject it, one failed comparison is enough: use OR.

Write it precisely

Write Mark > 50, not “Mark is greater than 50”. Write each comparison in full: Mark >= 0 AND Mark <= 100, never 0 <= Mark <= 100.

Your turn

1 Which check does UNTIL LENGTH(Pin) = 4 carry out?

2 A height must be from 50 to 250. Write the UNTIL line of its range check.

3 Write a presence check that asks for Town until something is entered, with an error message.

1 a length check · 2 UNTIL Height >= 50 AND Height <= 250 · 3 for example:

Presence check · Town
DECLARE Town : STRING
REPEAT
OUTPUT "Enter your town"
INPUT Town
IF Town = ""
THEN
OUTPUT "Town must not be blank"
ENDIF
UNTIL Town <> ""
Tick what you can do now
Practise with s26/22 Q3(c); m26/22 Q2(c); s26/23 Q3(c); m25/22 Q4(b)(ii) (older paper: stand-alone whole-number loop)
4 / 15
0478 · Unit 7 · Algorithm design and problem-solving
Revisionbyexamplicity

Checking each value before it is stored

§7 · Algorithms

An array is only useful if every value in it can be trusted, so each value is checked before it is stored. That takes two loops for two different jobs: an outer count-controlled loop selects the array position; an inner condition-controlled loop keeps asking until that position has a valid value.

The program: an outer loop and an inner check

There are four inputs for only three places in Values, so one of them must be turned away. Find the line that stores a value, and what has to be true before it runs.

Fill predeclared Values[0:2]inputs: 7, 3.5, 0, 12
 1DECLARE Index : INTEGER
 2DECLARE Score : REAL
 3FOR Index ← 0 TO 2
 4REPEAT
 5OUTPUT "Enter a whole-number score from 0 to 100"
 6INPUT Score
 7IF ROUND(Score, 0) <> Score OR Score < 0 OR Score > 100
 8THEN
 9OUTPUT "Invalid score - enter it again"
10ENDIF
11UNTIL ROUND(Score, 0) = Score AND Score >= 0 AND Score <= 100
12Values[Index] ← Score
13NEXT Index
14OUTPUT "Three scores stored"
Input attemptIndexEffect
70Valid: store Values[0] = 7, then move to index 1
3.51Not a whole number: show error; keep index 1
01Valid lower limit: store Values[1] = 0
122Store Values[2] = 12; then output completion message

Line by line: where each job is done

  1. 7
    The IF rejects with OR: Score < 0 OR Score > 100.
  2. 11
    The UNTIL accepts with AND: Score >= 0 AND Score <= 100.
  3. 12
    Store the value only after validation.
  4. 13
    Move to the next index only after a valid value is stored: counting attempts instead would leave a gap or an invalid value.
  5. 14
    Output the completion message after the outer loop.

Line by line: where each job is done

  1. 7
    The IF rejects with OR: Score < 0 OR Score > 100.
  2. 11
    The UNTIL accepts with AND: Score >= 0 AND Score <= 100.
  3. 12
    Store the value only after validation.
  4. 13
    Move to the next index only after a valid value is stored: counting attempts instead would leave a gap or an invalid value.
  5. 14
    Output the completion message after the outer loop.
The rejected attempt: input 2
The inner loop goes round again. Index is still 1. This is the blue row of the whole run.
LineStatement that runsScoreOUTPUTWritesWhat happens
5OUTPUT "Enter a whole-number score from 0 to 100"Enter a whole-number score from 0 to 100OUTPUT Enter a whole-number score from 0 to 100
6INPUT Score3.5Score 3.5the next unused input
the next unused input
7IF ROUND(Score, 0) <> Score OR …test ROUND(3.5, 0) = 4, not 3.5: true, so the next OUTPUT runs
test ROUND(3.5, 0) = 4, not 3.5: true, so the next OUTPUT runs
9OUTPUT "Invalid score - enter it again"Invalid score - enter it againOUTPUT Invalid score - enter it again
11UNTIL ROUND(Score, 0) = Score AND …test false, so the REPEAT runs again; nothing is stored
test false, so the REPEAT runs again; nothing is stored

Trace every input

IndexScoreValues[Index]OUTPUTWhat decided it
input 1077Enter a whole-number score from 0 to 1007 is valid: UNTIL is true, so it is stored and Index moves on
7 is valid: UNTIL is true, so it is stored and Index moves on
input 213.5Enter a whole-number score from 0 to 100Invalid score - enter it again3.5 is not a whole number: error, UNTIL is false, so Index stays 1
3.5 is not a whole number: error, UNTIL is false, so Index stays 1
input 3100Enter a whole-number score from 0 to 1000 is valid (a limit, still valid): UNTIL is true, so it is stored and Index moves on
0 is valid (a limit, still valid): UNTIL is true, so it is stored and Index moves on
input 421212Enter a whole-number score from 0 to 10012 is valid: UNTIL is true, so it is stored and Index moves on
12 is valid: UNTIL is true, so it is stored and Index moves on
endThree scores storedIndex has passed 2, so the FOR loop ends
Index has passed 2, so the FOR loop ends
Your turn

1 Which loop chooses the array position, and which keeps asking for a valid value?

2 The inputs are 50, 101, 100, −1, 7. Which inputs cause an error message?

3 For the same inputs, what is stored in Values[0], Values[1] and Values[2]?

  1. 1
    the outer FOR loop chooses the position; the inner REPEAT … UNTIL loop keeps asking
  2. 2
    101 and −1 (out of range)
  3. 3
    Values[0] = 50, Values[1] = 100, Values[2] = 7
Tick what you can do now
Practise with s26/22 Q3(c); m26/22 Q2(c)
5 / 15
0478 · Unit 7 · Algorithm design and problem-solving
Revisionbyexamplicity

Validation, then verification

§7 · Algorithms

There is no point asking someone to confirm a code that is already the wrong length. So the checks go in order. First validate: the code must have 6 characters. Only then verify: ask for the code again and compare the two entries.

The algorithm: validate first, then verify

The inner REPEAT is the validation; the outer REPEAT is the verification. The table follows where control goes in each of the three cases.

Length, then double entry
DECLARE Code : STRING
DECLARE Confirm : STRING
REPEAT
REPEAT
OUTPUT "Enter a 6-character borrowing code"
INPUT Code
UNTIL LENGTH(Code) = 6
OUTPUT "Enter the same code again"
INPUT Confirm
IF Code <> Confirm
THEN
OUTPUT "Codes differ - restart"
ENDIF
UNTIL Code = Confirm
OUTPUT "Code accepted"
ConditionControl route
First entry has fewer or more than 6 charactersRepeat the inner input loop; do not request confirmation yet
Length is 6, but the entries differRestart the outer loop with a new first entry and validate it again
Length is 6 and both entries matchExit both loops and output acceptance

Trace what happens when each check fails

One user, five entries, in order. Each box is one input; under it are the check it met and what the algorithm does next.

1st entryAB12length ✗ask again1st entryAB1234length ✓now confirmconfirmAB1235match ✗restart1st entryXY9876length ✓now confirmconfirmXY9876match ✓Code accepted
1st entryAB12length ✗ask again1st entryAB1234length ✓now confirmconfirmAB1235match ✗restart1st entryXY9876length ✓now confirmconfirmXY9876match ✓Code accepted

What the checks can and cannot do

  • After a mismatch the first entry is not kept: the user starts again with a new code, which is length-checked again.
  • Double entry checks the data was typed the same way twice.
  • A visual check compares the data on screen with the original document.
  • Neither check can prove that the original data is true.
Your turn

1 Which line is the validation check, and which line is the verification check?

2 The inputs are QW12345, QW1234, QW1234. Which input fails, and which check does it fail?

3 Why is the second entry asked for only after the length check is passed?

  1. 1
    validation: UNTIL LENGTH(Code) = 6; verification: IF Code <> Confirm (with UNTIL Code = Confirm)
  2. 2
    QW12345 has 7 characters, so it fails the length check; QW1234 then passes it and the confirmation matches, so the output ends Code accepted
  3. 3
    so the user never confirms a code that is already invalid
Tick what you can do now
Practise with s26/23 Q3(c); m26/22 Q1
6 / 15
0478 · Unit 7 · Algorithm design and problem-solving
Revisionbyexamplicity

Choosing test data

§7 · Algorithm design

A program that works for 7 can still go wrong at 10 or 11, right at the edge of what it should accept. Good test data looks for those edges. Take one rule: the program accepts whole numbers from 5 to 10 inclusive.

Four types of test data for one rule

Each coloured value on the line is one type of test data. The table gives each type, its values in the same colours, and the outcome to expect.

accepted: 5 to 10rejectedrejected345extreme67normal8910extreme1112abnormalboundary 4 | 5boundary 10 | 11abnormal, not on the line−3out of range“ten”not a number7.5not whole
345extreme67normal8910extreme1112abnormalboundary4 | 5boundary10 | 11accepted5 to 10rejectedrejectedabnormal, not on the line−3out of range“ten”not a number7.5not whole
Type of test dataExample value(s)Expected outcome
Normal: valid data the program should accept7accepted
Abnormal: data that should be rejected (wrong range or type)12−3“ten”7.5rejected, with an error message
Extreme: the largest and smallest acceptable values510both accepted
Boundary: each acceptable limit and the value just beyond it4|510|114 rejected, 5 accepted · 10 accepted, 11 rejected

Other kinds of rule

Not every rule is a range of whole numbers. For each kind below, choose the boundary values and say whether each is accepted.

Strings

For “more than 9 characters”: boundary = 9 characters (rejected) and 10 characters (accepted). Spaces count as characters.

Decimals

Step by the stated precision. For 0.0 to 10.0 to 1 decimal place: test 10.0 (accepted) and 10.1 (rejected).

Negative ranges

For −100 to 0: boundary data is −101 and −100, and 0 and 1.

Test plan

Give the type of test, the value and the expected outcome. Link the reason to the rule: 4 is just below the smallest acceptable whole number, so it should be rejected.

Extreme data is only the acceptable limits. Boundary data is the limit and the value just outside it.
Your turn

1 A program accepts whole numbers from 20 to 30 inclusive. Give one normal test value.

2 Give the two extreme test values for the same rule.

3 Give the four boundary test values, each with its expected outcome.

1 any whole number from 21 to 29, e.g. 25 · 2 20 and 30 (both accepted) · 3 19 rejected, 20 accepted, 30 accepted, 31 rejected

accepted: 20 to 30rejectedrejected1920extreme21…25normal…2930extreme31boundary 19 | 20boundary 30 | 31
1920extreme21…25normal…2930extreme31boundary19 | 20boundary30 | 31accepted20 to 30rejectedrejected
Tick what you can do now
Practise with s26/23 Q3(a)(i), Q3(a)(ii); w25/22 Q3 (older paper: decimal-boundary test plan); w24/22 Q8 (older paper: justify paired boundary values)
7 / 15
0478 · Unit 7 · Algorithm design and problem-solving
Revisionbyexamplicity

Trace tables: following a program line by line

§7 · Algorithm design

You can find out what a program does without a computer: be the computer yourself. A dry run works through an algorithm by hand, one line at a time. Record each change to a variable and every output, prompts included, in the order they happen.

The program, and how to fill in a trace table

Algorithminputs: 20, 75, 50, 90
 1DECLARE Count : INTEGER
 2DECLARE Number : INTEGER
 3DECLARE Total : INTEGER
 4DECLARE Big : INTEGER
 5Total ← 0
 6Big ← 0
 7FOR Count ← 1 TO 4
 8OUTPUT "Enter a number"
 9INPUT Number
10Total ← Total + Number
11IF Number > 50
12THEN
13Big ← Big + 1
14ENDIF
15NEXT Count
16OUTPUT Total, " ", Big
One time round the loop: pass 2
Each line that runs is a row. Its value goes in that variable’s column. Together they make the blue row of the trace below.
LineStatement that runsCountNumberTotalBigOUTPUTWritesWhat happens
7FOR Count ← 1 TO 42Count 2
8OUTPUT "Enter a number"Enter a numberOUTPUT Enter a number
9INPUT Number75Number 75the next unused input
the next unused input
10Total ← Total + Number95Total 9520 + 75
20 + 75
11IF Number > 50test 75 > 50 is true, so line 13 runs
test 75 > 50 is true, so line 13 runs
13Big ← Big + 11Big 10 + 1
0 + 1

How to fill in a trace table

  1. 1
    Give each variable a column, and OUTPUT a column.
  2. 2
    Run one line at a time, in the order the lines run.
  3. 3
    When a line changes a variable, write the new value in its column.
  4. 4
    Start a new row each time round the loop.
  5. 5
    Leave a cell blank if its value did not change. Blank is not zero.
One time round the loop: pass 2
Each line that runs is a row. Its value goes in that variable’s column. Together they make the blue row of the trace below.
LineStatement that runsCountNumberTotalBigOUTPUTWritesWhat happens
7FOR Count ← 1 TO 42Count 2
8OUTPUT "Enter a number"Enter a numberOUTPUT Enter a number
9INPUT Number75Number 75the next unused input
the next unused input
10Total ← Total + Number95Total 9520 + 75
20 + 75
11IF Number > 50test 75 > 50 is true, so line 13 runs
test 75 > 50 is true, so line 13 runs
13Big ← Big + 11Big 10 + 1
0 + 1

Trace the whole run

CountNumberTotalBigOUTPUTWhat decided it
start00lines 5 and 6 set the starting values
lines 5 and 6 set the starting values
pass 112020Enter a number20 > 50 is false: Big is left blank
20 > 50 is false: Big is left blank
pass 2275951Enter a number75 > 50 is true: add 1 to Big
75 > 50 is true: add 1 to Big
pass 3350145Enter a number50 > 50 is false: Big is left blank
50 > 50 is false: Big is left blank
pass 44902352Enter a number90 > 50 is true: add 1 to Big
90 > 50 is true: add 1 to Big
end235 2Count has passed 4, so the loop ends and line 16 runs
Count has passed 4, so the loop ends and line 16 runs
Purpose. Total adds every input; Big adds 1 only when Number > 50. So the algorithm outputs the total of four numbers and how many are greater than 50.

Use the column headings you are given: some questions want a new row for every change. Skip a THEN branch whose condition is false.

Your turn

1 Which line runs only when its condition is true?

2 The inputs are 60, 10, 80, 40. What is output at the end?

3 Give the smallest whole-number input that adds 1 to Big.

  1. 1
    Big ← Big + 1 (only when Number > 50)
  2. 2
    190 2: Total = 60 + 10 + 80 + 40 = 190; only 60 and 80 are over 50, so Big = 2
  3. 3
    51, because 50 > 50 is false
Tick what you can do now
Practise with s26/23 Q5(a); m26/22 Q6(b); s24/23 Q5(a) (older paper: total and average trace)
8 / 15
0478 · Unit 7 · Algorithm design and problem-solving
Revisionbyexamplicity

Tracing a loop over the letters of a word

§7 · Algorithms

Spell balloon out loud and you meet two double letters, ll and oo. A program finds them the same way: it reads the word one character at a time and compares each one with the next. The last character has no next one, so the loop stops at length − 1.

A program can read a word one letter at a time, just as you spell it out. This one counts double letters, like the ll and oo in balloon. SUBSTRING counts characters from 1. The loop compares each character with the next one, so it stops at length − 1: the last character has no next one. Each word starts a fresh count.

The program and its inputs

Supplied input, in order: balloon, Y, tree, N, moss. Use the next value only when an INPUT statement is reached.

Count equal adjacent character pairs
 1DECLARE Word : STRING
 2DECLARE Choice : CHAR
 3DECLARE Position : INTEGER
 4DECLARE Doubles : INTEGER
 5REPEAT
 6OUTPUT "Enter a word"
 7INPUT Word
 8Doubles ← 0
 9FOR Position ← 1 TO LENGTH(Word) - 1
10IF SUBSTRING(Word, Position, 1) = SUBSTRING(Word, Position + 1, 1)
11THEN
12Doubles ← Doubles + 1
13ENDIF
14NEXT Position
15OUTPUT "Adjacent matches: ", Doubles
16OUTPUT "Another word? Y or N"
17INPUT Choice
18UNTIL Choice <> 'Y'
PositionPair in balloonDoubles after comparison
1ba0
2al0
3ll1
4lo1
5oo2
6on2

Restart and stop

  • The first result is 2. Choice Y restarts with Doubles = 0, rather than carrying 2 forward.
  • For tree, positions 1, 2, 3 compare tr, re, ee and give a result of 1.
  • Choice N ends the outer loop, so the last input, moss, is not read.
  • Write down the prompts and results before each choice. Do not use an input just because it is in the list.

balloon, character by character

Number the letters first: SUBSTRING counts from 1, so Position 1 is b.

1b2a3l4l5o6o7npass 3pass 5
  1. 1
    SUBSTRING(Word, Position, 1) is the character at Position.
  2. 2
    Equal neighbours sit at positions 3 and 4, and 5 and 6, so Doubles ends at 2.
One time round the FOR loop: balloon, position 3
Position 3 picks out character 3; Position + 1 picks out the next one. This is the blue row of the whole run.
LineStatement that runsPositionDoublesWritesWhat happens
9FOR Position ← 1 TO LENGTH(Word) - 13Position 3Position runs 1 to LENGTH − 1 = 6
Position runs 1 to LENGTH − 1 = 6
10IF SUBSTRING(Word, 3, 1) = SUBSTRING(Word, 4, 1)test l = l is true, so line 12 runs
test l = l is true, so line 12 runs
12Doubles ← Doubles + 11Doubles 10 + 1
0 + 1

Trace the whole run

InputPositionPairDoublesOUTPUTWhat decided it
wordballoon0Enter a wordINPUT Word reads the next input; Doubles is reset to 0
INPUT Word reads the next input; Doubles is reset to 0
pass 11bab = a is false
b = a is false
pass 22ala = l is false
a = l is false
pass 33ll1l = l is true: add 1 to Doubles
l = l is true: add 1 to Doubles
pass 44lol = o is false
l = o is false
pass 55oo2o = o is true: add 1 to Doubles
o = o is true: add 1 to Doubles
pass 66ono = n is false
o = n is false
resultAdjacent matches: 2Position has passed 6, so the FOR loop ends
Position has passed 6, so the FOR loop ends
choiceYAnother word? Y or NChoice is Y: UNTIL is false, so the REPEAT runs again
Choice is Y: UNTIL is false, so the REPEAT runs again
wordtree0Enter a wordINPUT Word reads the next input; Doubles is reset to 0
INPUT Word reads the next input; Doubles is reset to 0
pass 11trt = r is false
t = r is false
pass 22rer = e is false
r = e is false
pass 33ee1e = e is true: add 1 to Doubles
e = e is true: add 1 to Doubles
resultAdjacent matches: 1Position has passed 3, so the FOR loop ends
Position has passed 3, so the FOR loop ends
choiceNAnother word? Y or NChoice is N: UNTIL is true, so the loop ends
Choice is N: UNTIL is true, so the loop ends
endmoss is never read
moss is never read

Restart and stop

  • Choice Y restarts with Doubles = 0, rather than carrying 2 forward.
  • Choice N ends the outer loop, so the last input, moss, is not read.
  • Do not use an input just because it is in the list.
Your turn

1 How many times does the FOR loop run for the word moss?

2 What is output as the number of adjacent matches for coffee?

3 The inputs are bee, N, add. Write every output in order. Is add read?

  1. 1
    3 times (positions 1 to LENGTH − 1 = 3)
  2. 2
    2: ff and ee
  3. 3
    Enter a word, Adjacent matches: 1, Another word? Y or N; add is not read, because N ends the loop
Tick what you can do now
Practise with s26/22 Q6(a), Q6(b); m26/22 Q6(a), Q6(b)
9 / 15
0478 · Unit 7 · Algorithm design and problem-solving
Revisionbyexamplicity

Finding and correcting algorithm errors

§7 · Algorithm design

One wrong line can make a whole algorithm give the wrong answer, and still look fine at a glance. To correct an error, give the line number and the corrected line. Then trace a few values to check the correction works.

Find the errors in this algorithm

The algorithm should input 10 positive whole numbers and output the highest. Starting Highest at 0 is safe because every input is positive; it would fail if every input could be negative.

Algorithm with errors
01 DECLARE Highest : STRING
02 DECLARE Number : INTEGER
03 DECLARE Count : INTEGER
04 Highest ← 0
05 FOR Count ← 1 TO 10
06     OUTPUT Number
07     IF Number < Highest
08       THEN
09         Highest ← Number
10     ENDIF
11 ENDWHILE
12 OUTPUT "Highest: ", Highest
Line and correctionWhy it is needed
01 · DECLARE Highest : INTEGERHighest holds a number, not text
06 · INPUT NumberA value must be entered before it can be compared
07 · IF Number > HighestOnly a larger input replaces the maximum
11 · NEXT CountClose the FOR loop using its own counter

Test the correction with a few values

A correction is only right if the algorithm now gives the right answer. The first three inputs are 12, 30, 7. Lines 01, 06 and 11 are already corrected.

NumberHighest, line 07 as writtenHighest, line 07 correctedWhat decided it
start00line 04 sets Highest to 0 in both
line 04 sets Highest to 0 in both
input 11212as written 12 < 0 is false; corrected 12 > 0 is true
as written 12 < 0 is false; corrected 12 > 0 is true
input 23030as written 30 < 0 is false; corrected 30 > 12 is true
as written 30 < 0 is false; corrected 30 > 12 is true
input 37as written 7 < 0 is false; corrected 7 > 30 is false
as written 7 < 0 is false; corrected 7 > 30 is false
endHighest: 0Highest: 30line 12 outputs; as written, Highest never leaves 0
line 12 outputs; as written, Highest never leaves 0

Where errors usually hide

Most errors are one of three kinds. Use these checks to find the faulty line in any algorithm.

FaultHow to locate it
Wrong variable or array indexTrace which element was read and which one was changed; do not return element 1 for every match
Wrong start or loop limitCount the first and last elements reached; initialise totals before the adding loop
Wrong AND/OR or flag polarityTry an input that makes only one comparison true; follow when the loop repeats and when it stops
Your turn

This algorithm should output the average of five marks.

Algorithm with an error
01 DECLARE Count : INTEGER
02 DECLARE Mark : INTEGER
03 DECLARE Total : INTEGER
04 Total ← 0
05 FOR Count ← 1 TO 5
06     INPUT Mark
07     Total ← Mark
08 NEXT Count
09 OUTPUT Total / 5

1 Which line is wrong? Write the corrected line.

2 The marks are 3, 8, 5, 9, 2. What does the faulty algorithm output, and what should it output?

1 line 07: Total ← Total + Mark, so each mark is added to the running total · 2 faulty: Total ends as the last mark, 2, so it outputs 0.4; correct: 3 + 8 + 5 + 9 + 2 = 27, and 27 ÷ 5 = 5.4

Corrected
DECLARE Count : INTEGER
DECLARE Mark : INTEGER
DECLARE Total : INTEGER
Total ← 0
FOR Count ← 1 TO 5
INPUT Mark
Total ← Total + Mark
NEXT Count
OUTPUT Total / 5
Tick what you can do now
Practise with s26/22 Q5(a); m26/22 Q5(a); m25/22 Q6(a) (older paper: maximum and total errors)
10 / 15
0478 · Unit 7 · Algorithm design and problem-solving
Revisionbyexamplicity

Totalling and counting

§7 · Standard methods of solution

Given a list of numbers, the first two questions are usually: how much altogether, and how many of them? A total adds every value. A count adds 1 each time a value meets a condition.

The data and the program

Preloaded integer array Values, indexed 0 to 4. Find the total, and count how many values are 5 or more.

0417223946
Cambridge pseudocode
 1DECLARE Index : INTEGER
 2DECLARE Total : INTEGER
 3DECLARE Count : INTEGER
 4Total ← 0
 5Count ← 0
 6FOR Index ← 0 TO 4
 7Total ← Total + Values[Index]
 8IF Values[Index] >= 5
 9THEN
10Count ← Count + 1
11ENDIF
12NEXT Index
13OUTPUT "Total: ", Total
14OUTPUT "Count: ", Count
Python
Total = 0
Count = 0
for Index in range(5):
Total = Total + Values[Index]
if Values[Index] >= 5:
Count = Count + 1
print("Total:", Total)
print("Count:", Count)

State after each completed iteration

IndexValues[Index]TotalCount
start00
0440
17111
22131
39222
46283

Totalling and counting

Total ← Total + Value adds each value. Count ← Count + 1 adds one for each value that matches the condition.

Set both to 0 before the loop that updates them, never inside it.

Totalling and counting

Total ← Total + Value adds each value. Count ← Count + 1 adds one for each value that matches the condition.

Set both to 0 before the loop that updates them, never inside it.

One time round the loop: pass 2
Run one line, write one value. Then the next line. Together they make the blue row of the trace below.
LineStatement that runsIndexTotalCountWritesWhat happens
6FOR Index ← 0 TO 41Index 1
7Total ← Total + Values[Index]11Total 114 + Values[1], which is 7
4 + Values[1], which is 7
8IF Values[Index] >= 5test 7 >= 5 is true, so line 10 runs
test 7 >= 5 is true, so line 10 runs
10Count ← Count + 11Count 10 + 1
0 + 1

Trace every value

IndexValues[Index]TotalCountOUTPUTWhat decided it
start00lines 4 and 5 set both to 0
lines 4 and 5 set both to 0
pass 10440 + 4 = 4; 4 >= 5 is false: Count is left blank
0 + 4 = 4; 4 >= 5 is false: Count is left blank
pass 2171114 + 7 = 11; 7 >= 5 is true: add 1 to Count
4 + 7 = 11; 7 >= 5 is true: add 1 to Count
pass 3221311 + 2 = 13; 2 >= 5 is false: Count is left blank
11 + 2 = 13; 2 >= 5 is false: Count is left blank
pass 43922213 + 9 = 22; 9 >= 5 is true: add 1 to Count
13 + 9 = 22; 9 >= 5 is true: add 1 to Count
pass 54628322 + 6 = 28; 6 >= 5 is true: add 1 to Count
22 + 6 = 28; 6 >= 5 is true: add 1 to Count
endTotal: 28Count: 3Index has passed 4, so the loop ends and both lines are output
Index has passed 4, so the loop ends and both lines are output
These examples index from 0. Exam arrays usually start at 1, e.g. Values[1:50]: always use the bounds given in the question.
Your turn

1 Values now holds 3, 8, 5, 1, 6. What is output for Total?

2 What is output for Count?

3 Change the algorithm so that Count counts the values less than 4. Which line changes, and to what? What is Count now?

  1. 1
    3 + 8 + 5 + 1 + 6 = 23
  2. 2
    3 (8, 5 and 6 are 5 or more)
  3. 3
    IF Values[Index] >= 5 becomes IF Values[Index] < 4; Count = 2 (3 and 1)
Tick what you can do now
Practise with s26/23 Q5(a); s24/22 Q6 (older paper: writing a totalling algorithm)
11 / 15
0478 · Unit 7 · Algorithm design and problem-solving
Revisionbyexamplicity

Maximum, minimum and average

§7 · Standard methods of solution

To find the tallest person in a queue, you walk along remembering the tallest so far, and swap only when someone beats them. A program does the same: it keeps the smallest and largest value seen so far, and replaces one when a new value beats it. The average is the total ÷ the number of values.

The data and the program

The same preloaded integer array Values, indexed 0 to 4. This time find the minimum, the maximum and the average (rounded to 1 decimal place).

0417223946
Cambridge pseudocode
 1DECLARE Index : INTEGER
 2DECLARE Total : INTEGER
 3DECLARE Minimum : INTEGER
 4DECLARE Maximum : INTEGER
 5Total ← 0
 6Minimum ← Values[0]
 7Maximum ← Values[0]
 8FOR Index ← 0 TO 4
 9Total ← Total + Values[Index]
10IF Values[Index] < Minimum
11THEN
12Minimum ← Values[Index]
13ENDIF
14IF Values[Index] > Maximum
15THEN
16Maximum ← Values[Index]
17ENDIF
18NEXT Index
19OUTPUT "Minimum: ", Minimum
20OUTPUT "Maximum: ", Maximum
21OUTPUT "Average: ", ROUND(Total / 5, 1)
Python
Total = 0
Minimum = Values[0]
Maximum = Values[0]
for Index in range(5):
Total = Total + Values[Index]
if Values[Index] < Minimum:
Minimum = Values[Index]
if Values[Index] > Maximum:
Maximum = Values[Index]
print("Minimum:", Minimum)
print("Maximum:", Maximum)
print("Average:", round(Total / 5, 1))

Iteration states: bold marks a new minimum or maximum

IndexValues[Index]MinimumMaximum
start44
0444
1747
2227
3929
4629

Starting values

  • Start both at the first value: this works for any data, even negative numbers.
  • Or start Maximum lower than any possible input (0 works for positive data) and Minimum higher than any possible input. A guessed limit may fail.
  • Average = total ÷ number of values = 28 ÷ 5 = 5.6.

Starting values

  • Start both at the first value: this works for any data, even negative numbers.
  • Or start Maximum lower than any possible input (0 works for positive data) and Minimum higher than any possible input. A guessed limit may fail.
  • Average = total ÷ number of values = 28 ÷ 5 = 5.6.
One time round the loop: pass 3
Both IFs are tested on every pass. Together the lines make the blue row of the trace below.
LineStatement that runsIndexTotalMinimumWritesWhat happens
8FOR Index ← 0 TO 42Index 2
9Total ← Total + Values[Index]13Total 1311 + 2
11 + 2
10IF Values[Index] < Minimumtest 2 < 4 is true, so the next line runs
test 2 < 4 is true, so the next line runs
12Minimum ← Values[Index]2Minimum 2a new smallest value
a new smallest value
14IF Values[Index] > Maximumtest 2 > 7 is false, so Maximum is not changed
test 2 > 7 is false, so Maximum is not changed

Trace every value

IndexValues[Index]TotalMinimumMaximumOUTPUTWhat decided it
start044Total ← 0; Minimum and Maximum ← Values[0], which is 4
Total ← 0; Minimum and Maximum ← Values[0], which is 4
pass 10444 < 4 is false · 4 > 4 is false
4 < 4 is false · 4 > 4 is false
pass 2171177 < 4 is false · 7 > 4 is true: new Maximum
7 < 4 is false · 7 > 4 is true: new Maximum
pass 3221322 < 4 is true: new Minimum · 2 > 7 is false
2 < 4 is true: new Minimum · 2 > 7 is false
pass 4392299 < 2 is false · 9 > 7 is true: new Maximum
9 < 2 is false · 9 > 7 is true: new Maximum
pass 546286 < 2 is false · 6 > 9 is false
6 < 2 is false · 6 > 9 is false
endMinimum: 2Maximum: 9Average: 5.6ROUND(28 / 5, 1) = 5.6
ROUND(28 / 5, 1) = 5.6
Your turn

1 Values now holds 12, 5, 18, 7, 4. What are Minimum and Maximum at the start?

2 What are Minimum and Maximum after Index 2 has been processed?

3 What three lines are output at the end?

  1. 1
    both 12, the first value
  2. 2
    Minimum 5, Maximum 18
  3. 3
    Minimum: 4, Maximum: 18, Average: 9.2 (12 + 5 + 18 + 7 + 4 = 46, and 46 ÷ 5 = 9.2)
Tick what you can do now
Practise with s26/21 Q10(a); m25/22 Q6(b), Q6(c) (older paper: rounded mean and minimum amendment)
12 / 15
0478 · Unit 7 · Algorithm design and problem-solving
Revisionbyexamplicity

A flowchart that finds the largest value

§7 · Algorithms

The maximum method can be drawn as well as written, and a drawing is often what you are asked to change. Follow the numbered circles as the flowchart reads five whole numbers and outputs the largest.

STARTINPUT ValueMaximum ← ValueCount ← 1INPUT ValueValue > Maximum?YesMaximum ← ValueNoCount ← Count + 1Count = 5?NoYesOUTPUT MaximumSTOP12345

How it finds the maximum

  1. 1
    The first input becomes Maximum. Count starts at 1.
  2. 2
    Each new input is compared with Maximum.
  3. 3
    Maximum is replaced only if the new value is larger.
  4. 4
    Count goes up by 1 every time, whatever the comparison.
  5. 5
    When Count reaches 5 the loop ends and Maximum is output.

Inputs 4, 7, 2, 9, 6. Blue marks where Maximum changes.

Value47296
Maximum47799
Count12345

Starting from the first input also works when every number is negative.

Amend it: reject negative inputs

A slip of the finger can type −7, so the amended flowchart checks each input before it is compared with Maximum.

INPUT ValueValue >= 0?NoaskagainYescarry on: now use Value
  • Put the new decision after each INPUT, before Value is used.
  • Yes carries on. No goes back to that INPUT.
  • Do not add 1 to Count for a rejected input.
  • For positive numbers only, test Value > 0: it also rejects zero.
To describe an amendment, say where the new symbol goes and where each of its exits leads.
Your turn

1 Which symbol holds Count = 5?, and what labels go on its exits?

2 The inputs are 3, 8, 8, 1, 5. How does Maximum change, and what is output?

3 What would you change so the flowchart outputs the minimum instead?

  1. 1
    a decision diamond, with Yes and No exits
  2. 2
    3 → 8 → 8 → 8 → 8; the output is 8 (the second 8 is not larger, so Maximum is not replaced)
  3. 3
    change the decision to Value < Minimum?, and use a variable Minimum in place of Maximum in every box
Tick what you can do now
Practise with s26/21 Q10(a), Q10(b); s26/23 Q5(b)
13 / 15
0478 · Unit 7 · Algorithm design and problem-solving
Revisionbyexamplicity

Bubble sort

§7 · Standard methods of solution

Lining up a class by height, you swap any two neighbours standing the wrong way round, then walk the line again until nobody moves. A bubble sort compares each pair of adjacent values in the same way, and repeats whole passes until a pass makes no swaps. Sort the same Values = [4, 7, 2, 9, 6] into ascending order.

Watch the passes

Each row is the whole list after one pass. An orange outline marks a pair that swapped; a blue value has reached its final place.

Start47296After pass 142769swaps 7 ↔ 2, 9 ↔ 6→ another passAfter pass 224679swaps 4 ↔ 2, 7 ↔ 6→ another passAfter pass 324679no swaps→ sorted, stop
Pass 1: one comparison at a time47296startIndex 047296keepIndex 142796swapIndex 242796keepIndex 342769swapAfter each pass: blue is in its final placepass 1427692 swapspass 2246792 swapspass 324679stopAmber: the pair just swapped

Why it stops

After each pass the largest remaining value has “bubbled” to its final place (highlighted). Pass 3 makes no swaps, so the list is sorted.

In code, one pass is the FOR loop. The REPEAT runs pass after pass until Swapped is still FALSE at the end of one.

Cambridge pseudocode
 1DECLARE Index : INTEGER
 2DECLARE Temp : INTEGER
 3DECLARE Swapped : BOOLEAN
 4REPEAT
 5Swapped ← FALSE
 6FOR Index ← 0 TO 3
 7IF Values[Index] > Values[Index + 1]
 8THEN
 9Temp ← Values[Index]
10Values[Index] ← Values[Index + 1]
11Values[Index + 1] ← Temp
12Swapped ← TRUE
13ENDIF
14NEXT Index
15UNTIL NOT Swapped
16FOR Index ← 0 TO 4
17OUTPUT Values[Index]
18NEXT Index
Python
Swapped = True
while Swapped:
Swapped = False
for Index in range(4):
if Values[Index] > Values[Index + 1]:
Temp = Values[Index]
Values[Index] = Values[Index + 1]
Values[Index + 1] = Temp
Swapped = True
for Index in range(5):
print(Values[Index])
One comparison, line by line: compare 2
A swap needs three lines and Temp. Together they make the blue row of the trace below.
LineStatement that runsIndexTempSwappedValuesWritesWhat happens
6FOR Index ← 0 TO 31Index 1
7IF Values[Index] > Values[Index + 1]test 7 > 2 is true, so the swap runs
test 7 > 2 is true, so the swap runs
9Temp ← Values[Index]7Temp 7keep 7 safe
keep 7 safe
10Values[Index] ← Values[Index + 1]4, 2, 2, 9, 6Values 4, 2, 2, 9, 62 is now in both places
2 is now in both places
11Values[Index + 1] ← Temp4, 2, 7, 9, 6Values 4, 2, 7, 9, 6Temp puts 7 back, one place along
Temp puts 7 back, one place along
12Swapped ← TRUETRUESwapped TRUE

Trace pass 1, comparison by comparison

IndexTempSwappedValuesWhat decided it
startFALSE4, 7, 2, 9, 6each pass starts with Swapped ← FALSE
each pass starts with Swapped ← FALSE
compare 104 > 7 is false: no swap
4 > 7 is false: no swap
compare 217TRUE4, 2, 7, 9, 67 > 2 is true: Temp holds 7, then the two swap
7 > 2 is true: Temp holds 7, then the two swap
compare 327 > 9 is false: no swap
7 > 9 is false: no swap
compare 439TRUE4, 2, 7, 6, 99 > 6 is true: Temp holds 9, then the two swap
9 > 6 is true: Temp holds 9, then the two swap
endSwapped is TRUE, so UNTIL NOT Swapped is false: another pass
Swapped is TRUE, so UNTIL NOT Swapped is false: another pass

Swap, sort the other way, stop early

Swap with a temporary variable

Temp holds one value so it is not overwritten.

Descending order

Change the comparison to <: swap when the left value is smaller.

More efficient

Each pass can check one fewer pair (the end is already sorted), and the Swapped flag stops the sort when a pass makes no swaps.

Your turn

1 Which two values are compared first?

2 Sort 5, 1, 4, 2 into ascending order. What is the list after pass 1?

3 How many passes are made before the sort stops? Why does it stop?

  1. 1
    the first two, Values[0] and Values[1]
  2. 2
    1, 4, 2, 5: swaps 5 ↔ 1, 5 ↔ 4, 5 ↔ 2
  3. 3
    3 passes: pass 2 gives 1, 2, 4, 5, and pass 3 makes no swaps, so Swapped stays FALSE
Tick what you can do now
Practise with s26/21 Q4; m26/22 Q5(a), Q5(c)
15 / 15