Algorithm Design and Problem-solving
Designing an algorithm: abstraction, decomposition, identifier tables, structured English, flowcharts, pseudocode, stepwise refinement and trace tables.
What an algorithm is
An algorithm is a list of clear steps that solves a problem. You can write it in three ways.
An algorithm is a solution to a problem, written as a sequence of defined steps. A recipe is a good picture of one.
A real algorithm has three things:
- Each step is clear enough to follow without guessing.
- The steps come in a fixed order.
- It comes to an end.
You can write the same algorithm in three ways:
| Way | What it looks like |
|---|---|
| Structured English | short numbered steps in English |
| Flowchart | a diagram of boxes and arrows |
| Pseudocode | lines that look like program code |
This topic shows how to write each one, and how to turn one into another.
Example:Most notes use one running example, class test results. Input five test marks. Then output the average, the highest mark, the lowest mark and how many students passed.
Abstraction: keep only what the problem needs
Abstraction keeps only the details a problem needs and leaves out the rest.
Abstraction means building a model (a simple copy) of a system. The model keeps only the details the problem needs, and leaves out the rest.
Its purpose is to filter out the information that the problem does not need. The solution is then simpler, so it is quicker to design and to program.
Which details are essential depends on the problem. So one real thing, such as a student, can have a different abstract model in each program that uses it.
| Program | Keeps | Leaves out |
|---|---|---|
| Report cards | name, marks, attendance | height, bus route |
| School bus | name, bus route | marks, height |
Pick a problem in the figure and see which details it keeps.
Watch out:Abstraction leaves out details. Decomposition breaks a problem into parts. Do not swap the two words.
Decomposition: sub-problems become modules
Decomposition breaks a big problem into small parts. Each part can become its own module.
Decomposition means breaking a problem into smaller sub-problems, and those into smaller ones again. You stop when each part can be solved on its own.
A sub-problem can become a program module: a procedure or a function.
Why modules help:
- You can write and test each one on its own.
- You can use it again wherever its task is needed.
- You can give it to a different programmer, so a team can share one large problem.
A structure chart shows the split, like a family tree:
- The whole problem goes in the top box.
- Its parts go in a row beneath it.
- Their parts go beneath them.
Remember:Topic 12.2 adds the data passed between the modules.
Naming the data: the identifier table
Before you write pseudocode, list every name you will use, with its data type and its job.
An identifier is a name for a variable or a constant. An identifier table lists every identifier the algorithm needs. For each one, give:
- its name
- its data type
- what it is for.
An example value, or the value it starts with, can go in the table too.
Good names say what the value is: TotalMarks, not T. The 9618 pseudocode guide allows single letters where they are the usual choice, such as i and j for array indexes.
Remember:An identifier is made of letters, digits and the underscore. It starts with a letter.
The identifier table for the class test program:
| Identifier | Data type | Description |
|---|---|---|
PassMark | INTEGER | Constant: the lowest pass mark, 50 |
Mark | INTEGER | The mark just input |
Count | INTEGER | Loop counter, 1 to 5 |
Total | INTEGER | Running total of the marks |
Highest | INTEGER | Highest mark so far |
Lowest | INTEGER | Lowest mark so far |
Passes | INTEGER | How many marks are a pass |
Input, process, output: sequence, selection and iteration
An algorithm takes input, processes it and gives output, using only three building blocks.
An algorithm takes input, processes it and produces output. It is built from three basic constructs (building blocks):
| Construct | What it does | In the class test program |
|---|---|---|
| Sequence | steps done one after another | the steps inside the loop, in order |
| Selection | IF or CASE chooses which steps run | three IF statements choose whether Passes, Highest and Lowest change |
| Iteration (repetition) | a loop repeats steps | a FOR loop repeats the same steps five times |
The class test program uses all three.
Example:Input the marks 67, 45, 82, 50 and 38. The program outputs an average of 56.4, a highest mark of 82, a lowest mark of 38 and 3 passes.
CONSTANT PassMark = 50 DECLARE Mark : INTEGER DECLARE Count : INTEGER DECLARE Total : INTEGER DECLARE Highest : INTEGER DECLARE Lowest : INTEGER DECLARE Passes : INTEGER Total ← 0 Passes ← 0 Highest ← -1 Lowest ← 101 FOR Count ← 1 TO 5 OUTPUT "Enter mark ", Count INPUT Mark Total ← Total + Mark IF Mark >= PassMark THEN Passes ← Passes + 1 ENDIF IF Mark > Highest THEN Highest ← Mark ENDIF IF Mark < Lowest THEN Lowest ← Mark ENDIF NEXT Count OUTPUT "Average: ", Total / 5 OUTPUT "Highest: ", Highest, " Lowest: ", Lowest OUTPUT "Passed: ", Passes
From structured English to pseudocode
Turn structured English into pseudocode one step at a time; each kind of step has its own statement.
Structured English describes an algorithm in short numbered steps, one action each. It uses words such as IF, OTHERWISE and REPEAT.
To turn it into pseudocode, take one step at a time:
| Structured English step | Becomes in pseudocode |
|---|---|
| an input step | INPUT |
| a calculation | an assignment (←) |
| if ... otherwise | IF ... ELSE |
| repeat | a loop |
Declare each variable as you meet it.
The figure shows the ticket rules as five steps:
- under 5 is free
- under 18, or 65 and over, pays 3000
- everyone else pays 5000.
Tap a step to light the lines it became.
Example:For Age 12 the program outputs a price of 3000.
DECLARE Age : INTEGER DECLARE Price : INTEGER INPUT Age IF Age < 5 THEN Price ← 0 ELSE IF Age < 18 OR Age >= 65 THEN Price ← 3000 ELSE Price ← 5000 ENDIF ENDIF OUTPUT "Ticket price: ", Price
Flowcharts: the same algorithm as a picture
A flowchart draws an algorithm as a picture: each kind of step has its own shape.
A flowchart draws an algorithm with standard symbols. Flow lines (arrows) join them and show the order.
| Symbol | Meaning |
|---|---|
| rounded box (a terminator) | START and END |
| parallelogram | an input or an output |
| rectangle | a process |
| diamond | a decision: exactly two exits, labelled Yes and No |
| rectangle with double sides | a call to a module |
Turning one into the other:
- Pseudocode to flowchart: give each statement its symbol, and join them in order.
- Flowchart to pseudocode: follow the arrows from
START, and write what each symbol says.
Exam:A decision always has exactly two exits, and both are labelled.
Loops in a flowchart: test at the top or the bottom
A loop tests its condition at the top (WHILE) or at the bottom (REPEAT), and that changes how it behaves.
In a flowchart, a loop is a flow line going back up.
| Pre-condition loop | Post-condition loop | |
|---|---|---|
| Pseudocode | WHILE | REPEAT ... UNTIL |
| Where is the decision? | before the steps it repeats | after them |
| How often can it run? | maybe zero times | always at least once |
| It stops when its condition is | FALSE | TRUE |
| Keep asking until a mark is 0 to 100 | WHILE Mark < 0 OR Mark > 100 | UNTIL Mark >= 0 AND Mark <= 100 |
Remember:For the same job, the two conditions are opposites. REPEAT stops on TRUE; WHILE stops on FALSE.
DECLARE Mark : INTEGER REPEAT OUTPUT "Enter a mark (0 to 100)" INPUT Mark UNTIL Mark >= 0 AND Mark <= 100 OUTPUT "Enter a mark (0 to 100)" INPUT Mark WHILE Mark < 0 OR Mark > 100 OUTPUT "Out of range. Enter a mark (0 to 100)" INPUT Mark ENDWHILE
Stepwise refinement
Stepwise refinement breaks each step into smaller steps until every step is one line of code.
Stepwise refinement works like this:
- Write the whole task as one step.
- Break each step into smaller steps.
- Repeat until every step is detailed enough to be written as a line of code.
Think of "cook dinner". It becomes "make rice", "cook meat" and "set the table". Then "make rice" becomes "wash the rice", "add water", and so on.
| Decomposition | Stepwise refinement | |
|---|---|---|
| Splits a problem into | modules | smaller and smaller steps |
| Stops when | each part can be solved on its own | each step is a single statement |
The figure refines the class test task, one step per Next. After 6 refinements it is 4 levels deep. Every bottom box is one line of pseudocode.
The standard patterns: totalling, counting, highest, lowest, average
Four patterns appear again and again in Paper 2 algorithms: totalling, counting, highest and lowest, and average.
Learn where each part of a pattern goes: before, inside or after the loop.
| Pattern | Before the loop | Inside the loop | After the loop |
|---|---|---|---|
| Totalling | set the total to 0 | add each value to the total | - |
| Counting | set the count to 0 | add 1 each time the condition is TRUE | - |
| Highest and lowest | start with a value that every real value will beat, or with the first value input | replace it whenever a new value beats it | - |
| Average | - | - | divide the total by how many values there were |
Watch out:Work out the average after the loop, not inside it.
The trace table shows all four on the five marks.
// Totalling: start at 0 before // the loop, add inside it Total ← 0 Total ← Total + Mark // Counting: add 1 when the // condition is TRUE IF Mark >= PassMark THEN Passes ← Passes + 1 ENDIF // Highest (Lowest is the same, with <) IF Mark > Highest THEN Highest ← Mark ENDIF // Average: after the loop Average ← Total / 5
Logic statements in an algorithm
A logic statement is a TRUE-or-FALSE condition that says exactly when something happens.
A logic statement is a condition that is either TRUE or FALSE. It is built from comparisons joined by AND, OR and NOT. It states exactly when something happens.
| In words | As a logic statement |
|---|---|
| under 18, or 65 and over (the ticket program) | Age < 18 OR Age >= 65 |
| between 13 and 17 inclusive | (Age >= 13) AND (Age <= 17) |
The 9618 guide advises brackets to make the order clear, as in the three rules below.
Watch out:"Between 13 and 17 inclusive" is never Age >= 13 OR Age <= 17. That is TRUE for every age.
Concession ← (Age < 18) OR (Age >= 65) InClub ← (Age >= 13) AND (Age <= 17) Valid ← (Mark >= 0) AND (Mark <= 100)
Dry-running with a trace table
A trace table follows an algorithm by hand, line by line, to show what it does and where it goes wrong.
A dry run means following an algorithm by hand, line by line, with given data. A trace table records it: the value of each variable, and the output.
How to fill one in:
- Give each variable a column, plus one for
OUTPUT. - Write a value only when the variable changes.
- Move down a row when a column you need is already filled in the row you are on.
A dry run shows what an algorithm does and where it goes wrong.
Example:In the figure, one copy of the program starts Lowest at 0. No real mark is below 0, so Lowest never changes. That copy outputs a lowest mark of 0: a logic error.
RUN THE PSEUDOCODE
Write the pseudocode your syllabus uses and press Run. Assignment is the arrow — type <- and it works the same as ←. Both syllabuses are accepted, so OUTPUT and PRINT both work; where a word differs from the one the exam prints, the runner says so.
Press Run to see what it doesTotal ← 0
FOR Count ← 1 TO N
Total ← Total + Count
NEXT Count
OUTPUT TotalSTARTN = 5
| Count | Total | OUTPUT |
|---|---|---|
One row per pass through the loop. Leave a cell blank if it does not change on that pass.
KEY TERMS
CHECK YOURSELF
1.A program that prints report cards keeps each student's name, marks and attendance, and leaves out their height and bus route. What is this?
2.Which loop may run its body zero times?
3.Which logic statement is TRUE only for ages 13 to 17 inclusive?