6 missions. Guess, learn, then check. Your place is saved.
Mission 1Why does the Tube map ignore real distances, yet still work?
Mission 2How can you find a bug without running the program?
Mission 3Why is it called a bubble sort?
Mission 4How can a program average numbers if it doesn't know how many?
Mission 5You typed 41, not 14, for your age. Why did the form accept it?
Mission 6It passed every test. So why did it fail for an 18-year-old?
The specification points and sources are listed under the lesson: see Sources.
Mission 1
Why does the Tube map ignore real distances, yet still work?
Make a guess: Why does the Tube map ignore real distances, yet still work?
Algorithms · computational thinking
Breaking a problem down
Decomposition means breaking a problem into smaller sub-problems, each doing one identifiable task.
Each sub-problem can be broken down again until it is simple to solve.
Parts can be solved and tested separately, even by different people.
"Plan a Tube journey" splits into: find the nearest station, choose the route, work out the time.
Every computer system is made of sub-systems, made of further sub-systems.
Algorithms · computational thinking
Leaving detail out
Abstraction is removing unnecessary detail from a problem to focus on what matters.
Harry Beck's 1933 Tube map keeps the lines, the order of stations and where they connect.
It drops true distances and the real shape of the tunnels: travellers do not need them.
A program does the same: it models the real world with only the details the task needs.
Quick check
?A program models a snooker shot to predict where the balls will stop. Which detail should abstraction remove?
Algorithms · computational thinking
Inputs, processes and outputs
To analyse a problem, identify its inputs (data going in), processes (what is done to the data) and outputs (results).
Car park ticket machine: inputs are the hours wanted and the coins; the process works out the cost and change; outputs are the ticket and the change.
Also identify storage: data that must be kept, such as the price per hour.
Quick check
?A program asks for a room's length and width and the carpet price per m², then shows the total cost. Which of these is a process?
Algorithms · computational thinking
Structure diagrams
A structure diagram shows how a problem is decomposed, from the top down.
The top box is the whole problem. Each level below splits a box into its sub-problems.
Lines link each box to the sub-problems it is made of.
Boxes at the bottom are small enough to become a subroutine or a few lines of code.
Algorithms · computational thinking
Algorithms and algorithmic thinking
An algorithm is a sequence of steps that can be followed to complete a task.
The same algorithm can be written as a flowchart, as pseudocode or as program code.
Decomposition, abstraction and algorithms together are the core of computational thinking.
Quick check
?A team splits a school app into login, timetable and messages, and gives each part to a different programmer. Which idea is this?
Mission check
?Why does the Tube map ignore real distances, yet still work?
Beck's map is an abstraction. It removes detail a traveller does not need (true distances, tunnel shapes) and keeps what they do need (the lines, the order of stations and where to change), so planning a journey splits into simple sub-problems: which line, where to change, where to get off.
Mission 2
How can you find a bug without running the program?
Make a guess: How can you find a bug without running the program?
Algorithms · representing algorithms
Flowchart symbols
Symbol
Meaning
Rounded rectangle (terminator)
Start or Stop
Parallelogram
Input or output
Rectangle
Process, such as a calculation
Diamond
Decision: two exits, Yes/No or True/False
Rectangle with double sides
Subroutine (a separate sub-program)
Arrow (flow line)
The direction control flows
A flowchart shows an algorithm's steps and the order they happen in.
Quick check
?This flowchart is run with the input 10. What does it output?
Algorithms · representing algorithms
Pseudocode and code
Pseudocode writes an algorithm as structured statements, not tied to one programming language.
Cambridge exams use the pseudocode shown here; write precise conditions such as X > Y, not "X is greater than Y"
This algorithm loops while the count is above 0. Each time round it doubles the result and counts down by 1.
Cambridge pseudocode
DECLARE Count : INTEGER
DECLARE Result : INTEGER
Count ← 3
Result ← 1
WHILE Count > 0 DO
Result ← Result * 2
Count ← Count - 1
ENDWHILE
OUTPUT Result
Algorithms · representing algorithms
Trace tables
A dry run follows an algorithm by hand. A trace table records it: one column per variable, plus Output.
Add a row when a value changes. For screen 3, count goes 3, 2, 1, 0 and result goes 1, 2, 4, 8.
The pattern shows the purpose: it works out 2 to the power of the starting count.
Also record any user prompts the algorithm outputs.
Calculate
?Dry-run this algorithm. What does it output?
Cambridge pseudocode
DECLARE Num : INTEGER
DECLARE Steps : INTEGER
Num ← 37
Steps ← 0
WHILE Num > 1 DO
Num ← DIV(Num, 2)
Steps ← Steps + 1
ENDWHILE
OUTPUT Steps
Algorithms · representing algorithms
Errors in algorithms
A syntax error breaks the language's rules, e.g. a missing ENDIF. The code will not run.
A logic error: the code runs but gives a wrong result, e.g. > where ≥ was needed.
To fix a logic error, dry-run with test data, find where the trace goes wrong, correct it and retest.
Quick check
?This algorithm should output Pass for any mark of 50 or more. Which test mark shows that it has a logic error?
Cambridge pseudocode
DECLARE Mark : INTEGER
INPUT Mark
IF Mark > 50
THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF
Mission check
?How can you find a bug without running the program?
A dry run follows the algorithm by hand, recording every variable and output in a trace table. Where a value or output differs from what it should be, you have found the logic error and its line, without running anything.
Mission 3
Why is it called a bubble sort?
Make a guess: Why is it called a bubble sort?
Algorithms · sorting
One pass
A bubble sort compares each adjacent pair of items, starting at the front of the list.
If the pair is in the wrong order, swap them. Then move along one place and compare the next pair.
One trip through every pair is a pass.
After pass 1 of [5, 2, 8, 1, 4], the list is [2, 5, 1, 4, 8].
Your answer
?Do one pass of a bubble sort (into ascending order) on [6, 3, 9, 1, 7, 4]. What is the list after pass 1? Separate the numbers with commas.
Algorithms · sorting
Passes until sorted
Keep making passes. Each pass carries the largest unsorted item to its final place.
Stop after a pass that makes no swaps: the list must be sorted.
[5, 2, 8, 1, 4] needs 3 passes with swaps, then a 4th pass with none to confirm it.
A list of n items needs at most n − 1 passes that make swaps.
Calculate
?A bubble sort stops after a pass with no swaps. How many passes does it make on [6, 3, 9, 1, 7, 4], including that last pass?
Algorithms · sorting
Bubble sort in code
The inner loop is one pass: it compares item i with item i + 1 and swaps them if needed.
the array Items is declared ARRAY[1:6], so Index runs from 1 to 5.
A swap needs a temporary variable, temp, to hold one value.
swapped records whether the pass changed anything. The outer loop repeats until a pass makes no swaps.
Cambridge pseudocode
DECLARE Items : ARRAY[1:6] OF INTEGER
DECLARE Index : INTEGER
DECLARE Temp : INTEGER
DECLARE Swapped : BOOLEAN
REPEAT
Swapped ← FALSE
FOR Index ← 1 TO 5
IF Items[Index] > Items[Index + 1]
THEN
Temp ← Items[Index]
Items[Index] ← Items[Index + 1]
Items[Index + 1] ← Temp
Swapped ← TRUE
ENDIF
NEXT Index
UNTIL Swapped = FALSE
Quick check
?A student swaps two items without a temporary variable. Before these two lines run, the first item holds 9 and the second holds 2. What do they hold afterwards?
Quick on a nearly sorted list: a sorted list needs just one pass.
Slow on large lists: with 1,000 items, each pass makes 999 comparisons, and it may need 999 passes with swaps.
Calculate
?The code on screen 5 compares 5 pairs in every pass. How many comparisons does it make in total to sort [6, 3, 9, 1, 7, 4]?
Mission check
?Why is it called a bubble sort?
In each pass, swaps carry the largest unsorted item along the list until it reaches its place at the end, like a bubble rising to the top of a drink. Each pass bubbles one more item into place, and a pass with no swaps shows the list is sorted.
Mission 4
How can a program average numbers if it doesn't know how many?
Make a guess: How can a program average numbers if it doesn't know how many?
Algorithms · standard methods
Totalling
Totalling keeps a running total. Set the total to 0 before the loop.
Inside the loop, add each new value to the total.
Forgetting to set the total to 0 first is a common error.
With marks 12, 7, 9 and 15, the total goes 0 → 12 → 19 → 28 → 43.
Cambridge pseudocode
DECLARE Total : INTEGER
DECLARE Index : INTEGER
DECLARE Mark : INTEGER
Total ← 0
FOR Index ← 1 TO 4
INPUT Mark
Total ← Total + Mark
NEXT Index
OUTPUT Total
Algorithms · standard methods
Counting and the average
Counting adds 1 each time something happens. Set the count to 0 before the loop.
If you do not know how many values are coming, loop until a value arrives that cannot be real data, such as −1 for a mark. This stop value is not added or counted.
After the loop, average = total ÷ count. Check the count is above 0 first.
Cambridge pseudocode
DECLARE Total : INTEGER
DECLARE Count : INTEGER
DECLARE Mark : INTEGER
Total ← 0
Count ← 0
INPUT Mark
WHILE Mark <> -1 DO
Total ← Total + Mark
Count ← Count + 1
INPUT Mark
ENDWHILE
IF Count > 0
THEN
OUTPUT Total / Count
ENDIF
Calculate
?The program on screen 2 is given the inputs 14, 9, 20, 11, 6, −1. What does it output?
Algorithms · standard methods
Maximum and minimum
To find the maximum, set Max to the first value. Compare each value with Max and replace Max when a value is bigger.
The minimum works the same way, replacing Min when a value is smaller.
One loop can find the maximum, minimum and total; average = total ÷ number of values.
For scores 18, 25, 21, 30, 16: maximum 30, minimum 16, average 22.
Cambridge pseudocode
DECLARE Score : ARRAY[1:5] OF INTEGER
DECLARE Max : INTEGER
DECLARE Min : INTEGER
DECLARE Total : INTEGER
DECLARE Index : INTEGER
DECLARE Average : REAL
Max ← Score[1]
Min ← Score[1]
Total ← 0
FOR Index ← 1 TO 5
IF Score[Index] > Max
THEN
Max ← Score[Index]
ENDIF
IF Score[Index] < Min
THEN
Min ← Score[Index]
ENDIF
Total ← Total + Score[Index]
NEXT Index
Average ← Total / 5
OUTPUT Max, Min, Average
Calculate
?This algorithm checks the temperatures −3, −7, −1, −5. What does it output?
Cambridge pseudocode
DECLARE Temp : ARRAY[1:4] OF INTEGER
DECLARE Max : INTEGER
DECLARE Index : INTEGER
Max ← 0
FOR Index ← 1 TO 4
IF Temp[Index] > Max
THEN
Max ← Temp[Index]
ENDIF
NEXT Index
OUTPUT Max
Algorithms · standard methods
Linear search
A linear search checks each item in turn, from the first, until it finds the target or reaches the end.
The data can be in any order.
A Boolean flag, Found, stops the loop as soon as the item is found.
Cambridge pseudocode
DECLARE Names : ARRAY[1:5] OF STRING
DECLARE Found : BOOLEAN
DECLARE Index : INTEGER
DECLARE Target : STRING
Found ← FALSE
Index ← 1
INPUT Target
WHILE (Found = FALSE) AND (Index <= 5) DO
IF Names[Index] = Target
THEN
Found ← TRUE
ELSE
Index ← Index + 1
ENDIF
ENDWHILE
IF Found = TRUE
THEN
OUTPUT Target, " found at position ", Index
ELSE
OUTPUT Target, " not found"
ENDIF
Calculate
?The linear search on screen 8 runs with Names holding Kai, Ola, Ben, Zoe, Ann (Names[1] to Names[5]). The user inputs Ben. How many names does it compare with Target?
Algorithms · standard methods
The program development life cycle
Analysis: abstraction and decomposition of the problem; identify the problem and its requirements.
Design: decomposition, structure diagrams, flowcharts and pseudocode.
Coding: write the program code, with iterative testing of each part as it is written.
Testing: test the finished program with test data.
Mission check
?How can a program average numbers if it doesn't know how many?
Set a total and a count to 0. Each time a value arrives, add it to the total and add 1 to the count. When the end-of-data value arrives (such as −1 for marks), divide the total by the count.
Mission 5
You typed 41, not 14, for your age. Why did the form accept it?
Make a guess: You typed 41, not 14, for your age. Why did the form accept it?
Programming · validation and authentication
What validation does
Validation is an automatic check that input is sensible and follows rules before the program uses it.
Invalid data is rejected, and the user is told why and asked again.
It stops bad data causing crashes or wrong results later.
Validation cannot tell whether data is correct: a mistyped value that still follows the rules gets through.
Programming · validation and authentication
Types of validation check
Check
What it tests
Example
Range check
a number is between limits
age 0 to 120
Length check
number of characters
password at least 8
Presence check
something was entered (not empty)
surname not blank
Type check: the data is the right data type, e.g. a whole number.
Format check: the data matches a set pattern, e.g. a date as DD/MM/YYYY.
Check digit: the last digit of a code such as an ISBN or barcode, calculated from the other digits. On entry it is recalculated; a mismatch shows a mistyped digit.
Quick check
?A field for a 4-digit PIN accepted 12. Which check would have rejected it?
Programming · validation and authentication
Writing a validation routine
Ask for input, test it, and keep asking until it passes.
A loop does this: the user cannot move on with invalid data.
This WHILE loop is a range check for 1 to 10.
Cambridge pseudocode
DECLARE Score : INTEGER
OUTPUT "Score 1 to 10"
INPUT Score
WHILE Score < 1 OR Score > 10 DO
OUTPUT "Must be 1 to 10"
INPUT Score
ENDWHILE
Calculate
?The user types three names in this order: an empty string, Al, then Amir. How many times is "Too short" output?
Cambridge pseudocode
DECLARE Name : STRING
INPUT Name
WHILE LENGTH(Name) < 3 DO
OUTPUT "Too short"
INPUT Name
ENDWHILE
OUTPUT "Hello ", Name
Programming · validation and authentication
Verification
Verification checks that data was entered or copied accurately, so it matches the original.
Double entry check: type the data twice; the computer compares the two and rejects a mismatch.
Visual check: the user reads the data on screen and compares it with the original.
Validation asks "is it sensible?"; verification asks "is it what was meant?". Typing 41 for 14 passes validation; comparing it with the original could catch it.
Mission check
?You typed 41, not 14, for your age. Why did the form accept it?
Validation checks that data is reasonable, such as an age from 0 to 120. 41 follows that rule, so it is accepted even though it is wrong. A verification check, such as reading the entry back, is how mistakes like this are caught.
Mission 6
It passed every test. So why did it fail for an 18-year-old?
Make a guess: It passed every test. So why did it fail for an 18-year-old?
Programming · testing
Why test?
Testing checks that a program works as intended and meets its requirements.
It finds errors so they can be fixed before users meet them.
A program can run without crashing and still give wrong results.
Passing a few easy tests proves little: choose test data that could expose errors.
Programming · testing
Normal, edge and wrong data
For a program that accepts whole numbers from 1 to 10:
Normal data: sensible values that should be accepted, e.g. 5.
Extreme data: the smallest and largest acceptable values, 1 and 10. Boundary data: each limit and the value just past it: 0 and 1, 10 and 11.
Abnormal data: data that should be rejected, e.g. ten or 15.
Calculate
?The rule is "adult ticket for 18 and over". Tests with ages 10, 30 and 50 all gave the right ticket. Which single age would show the error?
Cambridge pseudocode
DECLARE Age : INTEGER
INPUT Age
IF Age > 18
THEN
OUTPUT "Adult ticket"
ELSE
OUTPUT "Child ticket"
ENDIF
Quick check
?A program accepts whole numbers from 1 to 10. A tester types the word ten. What type of test data is this?
Programming · testing
Code that is easy to maintain
Other people (and you, later) must be able to read and change code. This is maintainability.
Meaningful identifiers: totalScore, not t.
Comments explain what each part of the code does.
Procedures and functions break code into named, reusable parts.
Mission check
?It passed every test. So why did it fail for an 18-year-old?
The code used > 18 when the rule needed ≥ 18, a mistake that only shows at exactly 18. Testing 10, 30 and 50 only tried normal values; a test at the edge of the range would have caught it.
Recap
Big ideas
Decomposition breaks a problem into sub-problems that can be solved separately.
Abstraction removes unnecessary detail so a model keeps only what the task needs.
Decompose a problem into inputs, processes, outputs and storage, and show it with a structure diagram.
Flowcharts, pseudocode and program code are three ways to write the same algorithm.
A trace table records each variable during a dry run; it reveals the output, the purpose and any logic error.
Syntax errors stop code running; logic errors give wrong results.
A bubble sort compares adjacent pairs and swaps any in the wrong order; one run through the list is a pass.
After each pass, the largest unsorted item is in place; stop when a pass makes no swaps.
It is simple and needs little memory, but it is slow for large lists.
Totalling: start at 0, add each value inside the loop. Counting: start at 0, add 1 each time.
Average = total ÷ count, worked out after the loop.
Max and min start at the first value; a linear search checks items in turn; the PDLC is analysis, design, coding, testing.
Validation automatically checks input is sensible, e.g. range, length and presence checks, and rejects data that breaks the rules; it cannot check data is correct.
Verification checks data matches the original: double entry and visual checks.
Choose test data of every kind: normal, at the edges of the range, and data that should be rejected (normal, extreme, boundary, abnormal).
Meaningful names, comments, indentation and subprograms make code easy to maintain.
🏆
Mini-lesson complete!
⭐⭐⭐
You've worked through Algorithm design and problem-solving for Cambridge IGCSE Computer Science (0478/0984). 🎉
Mission 1Why does the Tube map ignore real distances, yet still work?
Mission 2How can you find a bug without running the program?
Mission 3Why is it called a bubble sort?
Mission 4How can a program average numbers if it doesn't know how many?
Mission 5You typed 41, not 14, for your age. Why did the form accept it?
Mission 6It passed every test. So why did it fail for an 18-year-old?