Program development and decomposition
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
Understand the problem
- Requirements: what the program must do
- Abstraction: leave out detail that does not matter
- Decomposition: split the problem into smaller parts
Plan the solution
- Structure diagram
- Flowchart
- Pseudocode
Write the program
- Write program code from the design
- Iterative testing: test and correct each part as it is written
Check the whole program
- Run it with test data
- Compare actual results with expected results
- Correct the errors
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.
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.
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.
- 1Testing
- 2a structure diagram
- 3for example: input a pupil ID and a meal choice; process: check the pupil has enough credit; output: an order confirmation; storage: pupil credit balances
Flowcharts and validation loops
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.
The six symbols
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.
DECLARE Score : INTEGER OUTPUT "Score 0–100" INPUT Score WHILE Score < 0 OR Score > 100 DO OUTPUT "Try again" INPUT Score ENDWHILE OUTPUT "Accepted"
print("Score 0–100") Score = int(input()) while Score < 0 or Score > 100: print("Try again") Score = int(input()) print("Accepted")
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.
- 1a decision (diamond), with Yes and No exits
- 2an input/output parallelogram
- 3
Score 0–100,Try again,Try again,Accepted: 150 and −3 are out of range, 42 is accepted
Validation and verification
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.
| Check | Tests that… | Example rule | Accepts | Rejects |
|---|---|---|---|---|
| Range | a value is between a lower and an upper limit | score from 0 to 100 | 75 | 101−5 |
| Length | data has an exact, minimum or maximum number of characters | member code has 6 characters | LB0421 | AB12 |
| Type | data is the correct data type | age is a whole number | 15 | “ten”15.5 |
| Presence | data has been entered (not left blank) | surname must be entered | Patel | blank |
| Format | characters follow a set pattern | two letters then four digits | AB1234 | 1234AB |
| Check digit | the final digit matches one recalculated from the other digits | ISBN, barcode; the method below | 304752 | 304572 swapped |
A specified check-digit method
This method uses weights 1, 2, 3, 4, 5 and the remainder on division by 11.
3 × 1 + 0 × 2 + 4 × 3 + 7 × 4 + 5 × 5 = 68 → MOD(68, 11) = 2 → the code is stored as 304752
- 1The code is stored as 304752.
- 2When it is typed in again, the program works out the last digit again from the first five.
- 3If 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.
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?
- 1a length check
- 2verification, by double entry
- 32 × 1 + 1 × 2 + 3 × 3 + 0 × 4 + 4 × 5 = 33; MOD(33, 11) = 0, so the code is stored as 213040
Writing validation checks
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.
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
DECLARE Surname : STRING REPEAT OUTPUT "Enter your surname" INPUT Surname IF Surname = "" THEN OUTPUT "Surname must not be blank" ENDIF UNTIL Surname <> ""
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
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"
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:
- 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.
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:
DECLARE Town : STRING REPEAT OUTPUT "Enter your town" INPUT Town IF Town = "" THEN OUTPUT "Town must not be blank" ENDIF UNTIL Town <> ""
Checking each value before it is stored
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.
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 attempt | Index | Effect |
|---|---|---|
| 7 | 0 | Valid: store Values[0] = 7, then move to index 1 |
| 3.5 | 1 | Not a whole number: show error; keep index 1 |
| 0 | 1 | Valid lower limit: store Values[1] = 0 |
| 12 | 2 | Store Values[2] = 12; then output completion message |
Line by line: where each job is done
- 7The IF rejects with OR: Score < 0 OR Score > 100.
- 11The UNTIL accepts with AND: Score >= 0 AND Score <= 100.
- 12Store the value only after validation.
- 13Move to the next index only after a valid value is stored: counting attempts instead would leave a gap or an invalid value.
- 14Output the completion message after the outer loop.
Line by line: where each job is done
- 7The IF rejects with OR: Score < 0 OR Score > 100.
- 11The UNTIL accepts with AND: Score >= 0 AND Score <= 100.
- 12Store the value only after validation.
- 13Move to the next index only after a valid value is stored: counting attempts instead would leave a gap or an invalid value.
- 14Output the completion message after the outer loop.
| Line | Statement that runs | Score | OUTPUT | Writes | What happens |
|---|---|---|---|---|---|
| 5 | OUTPUT "Enter a whole-number score from 0 to 100" | Enter a whole-number score from 0 to 100 | OUTPUT Enter a whole-number score from 0 to 100 | ||
| 6 | INPUT Score | 3.5 | Score 3.5 | the next unused input | |
| the next unused input | |||||
| 7 | IF 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 | |||||
| 9 | OUTPUT "Invalid score - enter it again" | Invalid score - enter it again | OUTPUT Invalid score - enter it again | ||
| 11 | UNTIL 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
| Index | Score | Values | OUTPUT | What decided it | |
|---|---|---|---|---|---|
| input 1 | 0 | 7 | 7 | Enter a whole-number score from 0 to 100 | 7 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 2 | 1 | 3.5 | Enter a whole-number score from 0 to 100Invalid score - enter it again | 3.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 3 | 1 | 0 | 0 | Enter a whole-number score from 0 to 100 | 0 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 4 | 2 | 12 | 12 | Enter a whole-number score from 0 to 100 | 12 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 | |||||
| end | Three scores stored | Index has passed 2, so the FOR loop ends | |||
| Index has passed 2, so the FOR loop ends | |||||
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]?
- 1the outer FOR loop chooses the position; the inner REPEAT … UNTIL loop keeps asking
- 2101 and −1 (out of range)
- 3Values[0] = 50, Values[1] = 100, Values[2] = 7
Validation, then verification
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.
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"
| Condition | Control route |
|---|---|
| First entry has fewer or more than 6 characters | Repeat the inner input loop; do not request confirmation yet |
| Length is 6, but the entries differ | Restart the outer loop with a new first entry and validate it again |
| Length is 6 and both entries match | Exit 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.
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.
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?
- 1validation:
UNTIL LENGTH(Code) = 6; verification:IF Code <> Confirm(withUNTIL Code = Confirm) - 2QW12345 has 7 characters, so it fails the length check; QW1234 then passes it and the confirmation matches, so the output ends
Code accepted - 3so the user never confirms a code that is already invalid
Choosing test data
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.
| Type of test data | Example value(s) | Expected outcome |
|---|---|---|
| Normal: valid data the program should accept | 7 | accepted |
| Abnormal: data that should be rejected (wrong range or type) | 12−3“ten”7.5 | rejected, with an error message |
| Extreme: the largest and smallest acceptable values | 510 | both accepted |
| Boundary: each acceptable limit and the value just beyond it | 451011 | 4 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.
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
Trace tables: following a program line by line
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
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
| Line | Statement that runs | Count | Number | Total | Big | OUTPUT | Writes | What happens |
|---|---|---|---|---|---|---|---|---|
| 7 | FOR Count ← 1 TO 4 | 2 | Count 2 | |||||
| 8 | OUTPUT "Enter a number" | Enter a number | OUTPUT Enter a number | |||||
| 9 | INPUT Number | 75 | Number 75 | the next unused input | ||||
| the next unused input | ||||||||
| 10 | Total ← Total + Number | 95 | Total 95 | 20 + 75 | ||||
| 20 + 75 | ||||||||
| 11 | IF Number > 50 | test 75 > 50 is true, so line 13 runs | ||||||
| test 75 > 50 is true, so line 13 runs | ||||||||
| 13 | Big ← Big + 1 | 1 | Big 1 | 0 + 1 | ||||
| 0 + 1 | ||||||||
How to fill in a trace table
- 1Give each variable a column, and OUTPUT a column.
- 2Run one line at a time, in the order the lines run.
- 3When a line changes a variable, write the new value in its column.
- 4Start a new row each time round the loop.
- 5Leave a cell blank if its value did not change. Blank is not zero.
| Line | Statement that runs | Count | Number | Total | Big | OUTPUT | Writes | What happens |
|---|---|---|---|---|---|---|---|---|
| 7 | FOR Count ← 1 TO 4 | 2 | Count 2 | |||||
| 8 | OUTPUT "Enter a number" | Enter a number | OUTPUT Enter a number | |||||
| 9 | INPUT Number | 75 | Number 75 | the next unused input | ||||
| the next unused input | ||||||||
| 10 | Total ← Total + Number | 95 | Total 95 | 20 + 75 | ||||
| 20 + 75 | ||||||||
| 11 | IF Number > 50 | test 75 > 50 is true, so line 13 runs | ||||||
| test 75 > 50 is true, so line 13 runs | ||||||||
| 13 | Big ← Big + 1 | 1 | Big 1 | 0 + 1 | ||||
| 0 + 1 | ||||||||
Trace the whole run
| Count | Number | Total | Big | OUTPUT | What decided it | |
|---|---|---|---|---|---|---|
| start | 0 | 0 | lines 5 and 6 set the starting values | |||
| lines 5 and 6 set the starting values | ||||||
| pass 1 | 1 | 20 | 20 | Enter a number | 20 > 50 is false: Big is left blank | |
| 20 > 50 is false: Big is left blank | ||||||
| pass 2 | 2 | 75 | 95 | 1 | Enter a number | 75 > 50 is true: add 1 to Big |
| 75 > 50 is true: add 1 to Big | ||||||
| pass 3 | 3 | 50 | 145 | Enter a number | 50 > 50 is false: Big is left blank | |
| 50 > 50 is false: Big is left blank | ||||||
| pass 4 | 4 | 90 | 235 | 2 | Enter a number | 90 > 50 is true: add 1 to Big |
| 90 > 50 is true: add 1 to Big | ||||||
| end | 235 2 | Count has passed 4, so the loop ends and line 16 runs | ||||
| Count has passed 4, so the loop ends and line 16 runs | ||||||
Use the column headings you are given: some questions want a new row for every change. Skip a THEN branch whose condition is false.
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
Big ← Big + 1(only when Number > 50) - 2
190 2: Total = 60 + 10 + 80 + 40 = 190; only 60 and 80 are over 50, so Big = 2 - 351, because 50 > 50 is false
Tracing a loop over the letters of a word
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.
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'
| Position | Pair in balloon | Doubles after comparison |
|---|---|---|
| 1 | ba | 0 |
| 2 | al | 0 |
| 3 | ll | 1 |
| 4 | lo | 1 |
| 5 | oo | 2 |
| 6 | on | 2 |
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.
- 1SUBSTRING(Word, Position, 1) is the character at Position.
- 2Equal neighbours sit at positions 3 and 4, and 5 and 6, so Doubles ends at 2.
| Line | Statement that runs | Position | Doubles | Writes | What happens |
|---|---|---|---|---|---|
| 9 | FOR Position ← 1 TO LENGTH(Word) - 1 | 3 | Position 3 | Position runs 1 to LENGTH − 1 = 6 | |
| Position runs 1 to LENGTH − 1 = 6 | |||||
| 10 | IF 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 | |||||
| 12 | Doubles ← Doubles + 1 | 1 | Doubles 1 | 0 + 1 | |
| 0 + 1 | |||||
Trace the whole run
| Input | Position | Pair | Doubles | OUTPUT | What decided it | |
|---|---|---|---|---|---|---|
| word | balloon | 0 | Enter a word | INPUT Word reads the next input; Doubles is reset to 0 | ||
| INPUT Word reads the next input; Doubles is reset to 0 | ||||||
| pass 1 | 1 | ba | b = a is false | |||
| b = a is false | ||||||
| pass 2 | 2 | al | a = l is false | |||
| a = l is false | ||||||
| pass 3 | 3 | ll | 1 | l = l is true: add 1 to Doubles | ||
| l = l is true: add 1 to Doubles | ||||||
| pass 4 | 4 | lo | l = o is false | |||
| l = o is false | ||||||
| pass 5 | 5 | oo | 2 | o = o is true: add 1 to Doubles | ||
| o = o is true: add 1 to Doubles | ||||||
| pass 6 | 6 | on | o = n is false | |||
| o = n is false | ||||||
| result | Adjacent matches: 2 | Position has passed 6, so the FOR loop ends | ||||
| Position has passed 6, so the FOR loop ends | ||||||
| choice | Y | Another word? Y or N | Choice is Y: UNTIL is false, so the REPEAT runs again | |||
| Choice is Y: UNTIL is false, so the REPEAT runs again | ||||||
| word | tree | 0 | Enter a word | INPUT Word reads the next input; Doubles is reset to 0 | ||
| INPUT Word reads the next input; Doubles is reset to 0 | ||||||
| pass 1 | 1 | tr | t = r is false | |||
| t = r is false | ||||||
| pass 2 | 2 | re | r = e is false | |||
| r = e is false | ||||||
| pass 3 | 3 | ee | 1 | e = e is true: add 1 to Doubles | ||
| e = e is true: add 1 to Doubles | ||||||
| result | Adjacent matches: 1 | Position has passed 3, so the FOR loop ends | ||||
| Position has passed 3, so the FOR loop ends | ||||||
| choice | N | Another word? Y or N | Choice is N: UNTIL is true, so the loop ends | |||
| Choice is N: UNTIL is true, so the loop ends | ||||||
| end | moss 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.
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?
- 13 times (positions 1 to LENGTH − 1 = 3)
- 22: ff and ee
- 3
Enter a word,Adjacent matches: 1,Another word? Y or N; add is not read, because N ends the loop
Finding and correcting algorithm errors
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.
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 correction | Why it is needed |
|---|---|
01 · DECLARE Highest : INTEGER | Highest holds a number, not text |
06 · INPUT Number | A value must be entered before it can be compared |
07 · IF Number > Highest | Only a larger input replaces the maximum |
11 · NEXT Count | Close 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.
| Number | Highest, line 07 as written | Highest, line 07 corrected | What decided it | |
|---|---|---|---|---|
| start | 0 | 0 | line 04 sets Highest to 0 in both | |
| line 04 sets Highest to 0 in both | ||||
| input 1 | 12 | 12 | as written 12 < 0 is false; corrected 12 > 0 is true | |
| as written 12 < 0 is false; corrected 12 > 0 is true | ||||
| input 2 | 30 | 30 | as written 30 < 0 is false; corrected 30 > 12 is true | |
| as written 30 < 0 is false; corrected 30 > 12 is true | ||||
| input 3 | 7 | as written 7 < 0 is false; corrected 7 > 30 is false | ||
| as written 7 < 0 is false; corrected 7 > 30 is false | ||||
| end | Highest: 0 | Highest: 30 | line 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.
| Fault | How to locate it |
|---|---|
| Wrong variable or array index | Trace which element was read and which one was changed; do not return element 1 for every match |
| Wrong start or loop limit | Count the first and last elements reached; initialise totals before the adding loop |
| Wrong AND/OR or flag polarity | Try an input that makes only one comparison true; follow when the loop repeats and when it stops |
This algorithm should output the average of five marks.
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
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
Totalling and counting
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.
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
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
| Index | Values[Index] | Total | Count |
|---|---|---|---|
| start | 0 | 0 | |
| 0 | 4 | 4 | 0 |
| 1 | 7 | 11 | 1 |
| 2 | 2 | 13 | 1 |
| 3 | 9 | 22 | 2 |
| 4 | 6 | 28 | 3 |
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.
| Line | Statement that runs | Index | Total | Count | Writes | What happens |
|---|---|---|---|---|---|---|
| 6 | FOR Index ← 0 TO 4 | 1 | Index 1 | |||
| 7 | Total ← Total + Values[Index] | 11 | Total 11 | 4 + Values[1], which is 7 | ||
| 4 + Values[1], which is 7 | ||||||
| 8 | IF Values[Index] >= 5 | test 7 >= 5 is true, so line 10 runs | ||||
| test 7 >= 5 is true, so line 10 runs | ||||||
| 10 | Count ← Count + 1 | 1 | Count 1 | 0 + 1 | ||
| 0 + 1 | ||||||
Trace every value
| Index | Values | Total | Count | OUTPUT | What decided it | |
|---|---|---|---|---|---|---|
| start | 0 | 0 | lines 4 and 5 set both to 0 | |||
| lines 4 and 5 set both to 0 | ||||||
| pass 1 | 0 | 4 | 4 | 0 + 4 = 4; 4 >= 5 is false: Count is left blank | ||
| 0 + 4 = 4; 4 >= 5 is false: Count is left blank | ||||||
| pass 2 | 1 | 7 | 11 | 1 | 4 + 7 = 11; 7 >= 5 is true: add 1 to Count | |
| 4 + 7 = 11; 7 >= 5 is true: add 1 to Count | ||||||
| pass 3 | 2 | 2 | 13 | 11 + 2 = 13; 2 >= 5 is false: Count is left blank | ||
| 11 + 2 = 13; 2 >= 5 is false: Count is left blank | ||||||
| pass 4 | 3 | 9 | 22 | 2 | 13 + 9 = 22; 9 >= 5 is true: add 1 to Count | |
| 13 + 9 = 22; 9 >= 5 is true: add 1 to Count | ||||||
| pass 5 | 4 | 6 | 28 | 3 | 22 + 6 = 28; 6 >= 5 is true: add 1 to Count | |
| 22 + 6 = 28; 6 >= 5 is true: add 1 to Count | ||||||
| end | Total: 28Count: 3 | Index 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 | ||||||
Values[1:50]: always use the bounds given in the question.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?
- 13 + 8 + 5 + 1 + 6 = 23
- 23 (8, 5 and 6 are 5 or more)
- 3
IF Values[Index] >= 5becomesIF Values[Index] < 4; Count = 2 (3 and 1)
Maximum, minimum and average
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).
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)
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
| Index | Values[Index] | Minimum | Maximum |
|---|---|---|---|
| start | 4 | 4 | |
| 0 | 4 | 4 | 4 |
| 1 | 7 | 4 | 7 |
| 2 | 2 | 2 | 7 |
| 3 | 9 | 2 | 9 |
| 4 | 6 | 2 | 9 |
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.
| Line | Statement that runs | Index | Total | Minimum | Writes | What happens |
|---|---|---|---|---|---|---|
| 8 | FOR Index ← 0 TO 4 | 2 | Index 2 | |||
| 9 | Total ← Total + Values[Index] | 13 | Total 13 | 11 + 2 | ||
| 11 + 2 | ||||||
| 10 | IF Values[Index] < Minimum | test 2 < 4 is true, so the next line runs | ||||
| test 2 < 4 is true, so the next line runs | ||||||
| 12 | Minimum ← Values[Index] | 2 | Minimum 2 | a new smallest value | ||
| a new smallest value | ||||||
| 14 | IF Values[Index] > Maximum | test 2 > 7 is false, so Maximum is not changed | ||||
| test 2 > 7 is false, so Maximum is not changed | ||||||
Trace every value
| Index | Values | Total | Minimum | Maximum | OUTPUT | What decided it | |
|---|---|---|---|---|---|---|---|
| start | 0 | 4 | 4 | Total ← 0; Minimum and Maximum ← Values[0], which is 4 | |||
| Total ← 0; Minimum and Maximum ← Values[0], which is 4 | |||||||
| pass 1 | 0 | 4 | 4 | 4 < 4 is false · 4 > 4 is false | |||
| 4 < 4 is false · 4 > 4 is false | |||||||
| pass 2 | 1 | 7 | 11 | 7 | 7 < 4 is false · 7 > 4 is true: new Maximum | ||
| 7 < 4 is false · 7 > 4 is true: new Maximum | |||||||
| pass 3 | 2 | 2 | 13 | 2 | 2 < 4 is true: new Minimum · 2 > 7 is false | ||
| 2 < 4 is true: new Minimum · 2 > 7 is false | |||||||
| pass 4 | 3 | 9 | 22 | 9 | 9 < 2 is false · 9 > 7 is true: new Maximum | ||
| 9 < 2 is false · 9 > 7 is true: new Maximum | |||||||
| pass 5 | 4 | 6 | 28 | 6 < 2 is false · 6 > 9 is false | |||
| 6 < 2 is false · 6 > 9 is false | |||||||
| end | Minimum: 2Maximum: 9Average: 5.6 | ROUND(28 / 5, 1) = 5.6 | |||||
| ROUND(28 / 5, 1) = 5.6 | |||||||
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?
- 1both 12, the first value
- 2Minimum 5, Maximum 18
- 3
Minimum: 4,Maximum: 18,Average: 9.2(12 + 5 + 18 + 7 + 4 = 46, and 46 ÷ 5 = 9.2)
A flowchart that finds the largest value
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.
How it finds the maximum
- 1The first input becomes Maximum. Count starts at 1.
- 2Each new input is compared with Maximum.
- 3Maximum is replaced only if the new value is larger.
- 4Count goes up by 1 every time, whatever the comparison.
- 5When Count reaches 5 the loop ends and Maximum is output.
Inputs 4, 7, 2, 9, 6. Blue marks where Maximum changes.
| Value | 4 | 7 | 2 | 9 | 6 |
|---|---|---|---|---|---|
| Maximum | 4 | 7 | 7 | 9 | 9 |
| Count | 1 | 2 | 3 | 4 | 5 |
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.
- 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.
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?
- 1a decision diamond, with Yes and No exits
- 23 → 8 → 8 → 8 → 8; the output is 8 (the second 8 is not larger, so Maximum is not replaced)
- 3change the decision to Value < Minimum?, and use a variable Minimum in place of Maximum in every box
Linear search
To find a name on an unsorted list, you start at the top and read down until you find it. A linear search does the same: it checks each element in turn, from the first, until the target is found or every element has been checked. The array does not need to be sorted.
Search an array, element by element
Target 9 is compared with each element in turn. A ≠ moves Index on; the = sets Found to TRUE, so the last element is never checked.
In code, the WHILE condition does both jobs: it stops at the end of the array, or as soon as Found is TRUE.
DECLARE Index : INTEGER DECLARE Target : INTEGER DECLARE Found : BOOLEAN OUTPUT "Enter the value to find" INPUT Target Index ← 0 Found ← FALSE WHILE Index <= 4 AND NOT Found DO IF Values[Index] = Target THEN Found ← TRUE ELSE Index ← Index + 1 ENDIF ENDWHILE IF Found THEN OUTPUT "Found at index ", Index ELSE OUTPUT "Not found" ENDIF
print("Enter the value to find") Target = int(input()) Index = 0 Found = False while Index <= 4 and not Found: if Values[Index] == Target: Found = True else: Index = Index + 1 if Found: print("Found at index", Index) else: print("Not found")
Check the result and test the edges
Target 9
Found at index 3 after 4 comparisons.
Test the edges
Target at the first and last index, and a target that is not present: the loop must still stop.
Also accepted
A FOR loop that checks every element, with a variable such as Location ← -1 (or 0 if the array starts at 1) meaning “not found”.
1 Values holds 4, 7, 2, 9, 3. The target is 2. What is output, and how many comparisons are made?
2 The target is 5. What is output, and how many comparisons are made?
3 Why does the WHILE condition include NOT Found?
- 1
Found at index 2after 3 comparisons (4, 7, 2) - 2
Not foundafter 5 comparisons: every element is checked, then Index passes 4 and the loop stops - 3so the loop stops as soon as the target is found, and Index still holds its position
Bubble sort
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.
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.
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
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])
| Line | Statement that runs | Index | Temp | Swapped | Values | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 6 | FOR Index ← 0 TO 3 | 1 | Index 1 | ||||
| 7 | IF Values[Index] > Values[Index + 1] | test 7 > 2 is true, so the swap runs | |||||
| test 7 > 2 is true, so the swap runs | |||||||
| 9 | Temp ← Values[Index] | 7 | Temp 7 | keep 7 safe | |||
| keep 7 safe | |||||||
| 10 | Values[Index] ← Values[Index + 1] | 4, 2, 2, 9, 6 | Values 4, 2, 2, 9, 6 | 2 is now in both places | |||
| 2 is now in both places | |||||||
| 11 | Values[Index + 1] ← Temp | 4, 2, 7, 9, 6 | Values 4, 2, 7, 9, 6 | Temp puts 7 back, one place along | |||
| Temp puts 7 back, one place along | |||||||
| 12 | Swapped ← TRUE | TRUE | Swapped TRUE | ||||
Trace pass 1, comparison by comparison
| Index | Temp | Swapped | Values | What decided it | |
|---|---|---|---|---|---|
| start | FALSE | 4, 7, 2, 9, 6 | each pass starts with Swapped ← FALSE | ||
| each pass starts with Swapped ← FALSE | |||||
| compare 1 | 0 | 4 > 7 is false: no swap | |||
| 4 > 7 is false: no swap | |||||
| compare 2 | 1 | 7 | TRUE | 4, 2, 7, 9, 6 | 7 > 2 is true: Temp holds 7, then the two swap |
| 7 > 2 is true: Temp holds 7, then the two swap | |||||
| compare 3 | 2 | 7 > 9 is false: no swap | |||
| 7 > 9 is false: no swap | |||||
| compare 4 | 3 | 9 | TRUE | 4, 2, 7, 6, 9 | 9 > 6 is true: Temp holds 9, then the two swap |
| 9 > 6 is true: Temp holds 9, then the two swap | |||||
| end | Swapped 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.
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?
- 1the first two, Values[0] and Values[1]
- 21, 4, 2, 5: swaps 5 ↔ 1, 5 ↔ 4, 5 ↔ 2
- 33 passes: pass 2 gives 1, 2, 4, 5, and pass 3 makes no swaps, so Swapped stays FALSE