Abstraction: keep only what the task needs
A swimming club knows each member's address, birthday and swimming level, yet a reminder text needs only a name, a phone number and a date. Abstraction filters out information that is not necessary for a task and keeps the essential details; what is left is an abstract model, a simpler version of the system to design and program.
Task: a swimming club identifies members by Member ID and sends a personalised text to every member whose membership expires in the next seven days.
Follow each stored item: an arrow into the abstract model means the task uses it; every other item is left out.
An abstract model holds data and the operations on it
An abstract model also lists what the task does with the data. Give a reason from the task for every item kept, and for every item left out.
Operations this task needs
- Find the members whose expiry date is within the next 7 days.
- Create a personalised message for each of them.
- Send the text to each member's mobile number.
Check each exclusion against the task
| Not needed | Reason |
|---|---|
| Home address | the text is sent to a phone, not posted |
| Date of birth | age does not decide this expiry reminder |
| Email address | the channel is SMS |
| Swimming level | lane placement is a different task |
1 The club now posts a printed reminder letter instead of sending a text. Which stored item becomes essential, and which kept item is no longer needed?
2 What does abstraction filter out of a model?
3 Give one benefit of working from an abstract model.
- 1Home address becomes essential (the letter must be addressed); Mobile number is no longer needed
- 2information that is not necessary for the task: only the essential details are kept
- 3the solution is simpler to design and program, and it is tailored to what the users need
Decomposition: from a problem to modules
Renewing a membership online sounds like one job. Look closer and it is five: find the member, work out the fee, take the payment, update the expiry date and confirm. Decomposition breaks a problem down into sub-problems, each small enough to understand and solve on its own. Each one leads to a program module: a procedure or a function.
Describing decomposition
A definition that fits any task says nothing about this one. Describe the three moves in the context of the task, naming its own sub-problems.
Two kinds of module
Some modules just do a job; others do a job and hand back a value. Which kind it is decides how you call it.
| Procedure | Function | |
|---|---|---|
| What it does | carries out a task | carries out a task and returns a single value |
| How it is called | as a statement on its own:CALL UpdateExpiry(MemberID, 12) | as part of an expression:Fee ← CalculateFee("Junior", 12) |
Procedure
Carries out a task. Call it as a statement on its own:
CALL UpdateExpiry(MemberID, 12)
Function
Carries out a task and returns a single value. Use its result in an expression:
Fee ← CalculateFee("Junior", 12)
Benefits of decomposing into modules
- Smaller problems are easier to understand and solve.
- Each module is easier to program, test, debug and maintain.
- Modules can be given to different programmers or teams with different expertise.
- A module is written once and reused: no duplicated code, and a change is made in only one place.
1 Which of the five modules is called as a statement on its own with CALL, and why: TakePayment or SendConfirmation?
2 Write one pseudocode statement that stores the fee for a "Senior" member renewing for 6 months in Fee.
3 A café app takes table orders. Name two sub-problems it could be decomposed into.
- 1
SendConfirmation: it is a procedure, so it returns no value.TakePaymentis a function: it returns TRUE if paid, so it is used in an expression - 2Answer
Fee ← CalculateFee("Senior", 6) - 3for example: take the order, work out the bill, send the order to the kitchen, take the payment
CalculateFee() works out the renewal fee.Algorithms, identifiers and identifier tables
A school taking 100 students on a trip must book enough 45-seat coaches, and a guess will not do. It needs steps that give the right answer for any number of students. An algorithm is a solution to a problem expressed as a sequence of defined steps.
An algorithm is a solution to a problem expressed as a sequence of defined steps.
Input, process and output: coaches for a school trip
Read the program from line 4 down. The three boxes run the same lines with 100 students: what comes in, what is worked out, what is shown.
1CONSTANT CoachSeats = 45 2DECLARE Students, Coaches : INTEGER 3DECLARE EmptySeats : INTEGER 4INPUT Students 5Coaches ← Students DIV CoachSeats 6IF Students MOD CoachSeats > 0 THEN 7Coaches ← Coaches + 1 8ENDIF 9EmptySeats ← Coaches * CoachSeats - Students 10OUTPUT "Coaches needed: ", Coaches 11OUTPUT "Empty seats: ", EmptySeats
Identifiers for the calculation and booking details
A program is only readable if each name says what it holds. A row gives the name, its data type, and what the value means in this problem.
| Identifier | Data type | Purpose | Example value |
|---|---|---|---|
CoachSeats | INTEGER | the number of seats on one coach (a constant) | 45 |
Students | INTEGER | the number of students going on the trip | 100 |
Coaches | INTEGER | the number of coaches needed, rounded up | 3 |
EmptySeats | INTEGER | the number of seats left empty | 35 |
StudentName | STRING | a student's full name, for the booking list | "Ali Khan" |
TicketPrice | REAL | the price of one ticket in dollars | 12.50 |
HasPaid | BOOLEAN | TRUE once the student has paid | TRUE |
TripDate | DATE | the scheduled departure date | 12/04/2026 |
| Identifier · type | Meaning · example |
|---|---|
CoachSeatsINTEGER | the number of seats on one coach (a constant) Example: 45 |
StudentsINTEGER | the number of students going on the trip Example: 100 |
CoachesINTEGER | the number of coaches needed, rounded up Example: 3 |
EmptySeatsINTEGER | the number of seats left empty Example: 35 |
StudentNameSTRING | a student's full name, for the booking list Example: "Ali Khan" |
TicketPriceREAL | the price of one ticket in dollars Example: 12.50 |
HasPaidBOOLEAN | TRUE once the student has paid Example: TRUE |
TripDateDATE | the scheduled departure date Example: 12/04/2026 |
The first four rows occur in the program; the remaining rows illustrate related booking data.
Choosing identifier names
Test a name against all three rows: it must be allowed, and it must also say what it holds.
Valid TotalCost, Mark2, Max_Score | letters, digits and _ only; starts with a letter; meaningful |
Not valid 2ndMark, Total Cost, Cost$, NEXT | starts with a digit; has a space; has a symbol; is a keyword |
Poor X for a price | not meaningful: harder to understand, debug and maintain |
1 Trace the program with 130 students. What are Coaches and EmptySeats?
2 With 90 students, why is no extra coach added?
3 Which name is not a valid identifier, and why: Total_2, 2Total, TotalCost?
- 1
Coaches= 130 DIV 45 = 2; 130 MOD 45 = 40, not 0, so add 1: 3.EmptySeats= 3 × 45 − 130 = 5 - 290 MOD 45 = 0, so the IF condition is FALSE: 2 coaches, 0 empty seats
- 3
2Total: a name has to begin with a letter, not a digit
A, B and C do not show the purpose of the variable and make maintenance harder.Sequence, selection and iteration
However long an algorithm is, it is made of only three kinds of step: it does things in order, it makes choices, and it repeats. These are the three basic constructs: sequence, selection and iteration (repetition).
Sequence
Steps run one after another, in order. A swap needs Temp, or a value is overwritten.
Temp ← First First ← Second Second ← Temp
Selection
A condition decides which steps run. Only one of the two paths is taken.
IF Mark >= 40 THEN OUTPUT "Pass" ELSE OUTPUT "Fail" ENDIF
Iteration
Steps are repeated. Here the condition is tested before each pass.
Count ← 1 WHILE Count <= 5 OUTPUT Count * Count Count ← Count + 1 ENDWHILE
Identify the construct from its job
Knowing the name of a construct is only half of it; the other half is the job it does in this algorithm.
| Existing example | Why the construct is needed |
|---|---|
| Swap First and Second | sequence preserves First in Temp before overwriting it |
| Pass or fail | selection tests Mark against 40 and chooses one output |
| Squares 1 to 25 | iteration repeats the calculation for Count 1 through 5 |
1 Mark is 39. What does the selection output?
2 The swap is written without Temp: First ← Second, then Second ← First. First is 3 and Second is 8. What do they hold afterwards?
3 The iteration is changed to WHILE Count <= 3. What is output?
4 A password is asked for again until it is correct. Which construct is this?
- 1
"Fail": 39 >= 40 is FALSE, so the ELSE path runs - 2both hold 8: the 3 in
Firstwas overwritten before it was copied - 31, 4 and 9, each on its own line
- 4iteration: the input is repeated until a condition is met
Algorithm representations: structured English, pseudocode and flowcharts
Someone new to programming follows numbered steps, a programmer wants something close to code, and a picture shows every path at once. Structured English uses numbered commands in plain English, pseudocode uses keywords, identifiers and operators in no particular language, and a flowchart uses standard shapes joined by flow lines.
A plan for counting passes can be written in plain words, in something close to code, or as a picture, and each suits a different reader. Structured English uses numbered command statements in plain English. Pseudocode uses keywords, identifiers and operators, in no particular programming language. A flowchart uses standard shapes joined by flow lines.
Run the scores 72, 45, 50, 38, 91 through the flowchart and watch its counters; the numbered steps and the pseudocode must reach the same output.
Structured English
PassCount ← 0 FOR Count ← 1 TO 5 INPUT Score IF Score >= 50 THEN PassCount ← PassCount + 1 ENDIF NEXT Count OUTPUT PassCount
Scores 72, 45, 50, 38, 91 → output 3.
Flowchart symbols
In a flowchart, the shape of a box tells you what kind of statement is inside it.
1 The scores are 50, 49, 100, 0, 75. What does the algorithm output?
2 Which flowchart symbol holds INPUT Score?
3 Write structured English step 4 as pseudocode.
- 13: 50, 100 and 75 are at least 50; 49 and 0 are not
- 2the input / output parallelogram
- 3Answer
IF Score >= 50 THEN PassCount ← PassCount + 1 ENDIF
A loop that stops after a target count
Sometimes a loop should stop when a goal is reached, not after a fixed number of inputs. The pass counter read five scores and counted the successes; this loop stops after three successes and counts the attempts. Both use scores 72, 45, 50, 38, 91 and the same >= 50 test.
1PassCount ← 0 2Tries ← 0 3REPEAT 4INPUT Score 5Tries ← Tries + 1 6IF Score >= 50 THEN 7PassCount ← PassCount + 1 8ENDIF 9UNTIL PassCount = 3 10OUTPUT Tries
After each input and score test
Tries | Score | PassCount |
|---|---|---|
| 1 | 72 | 1 |
| 2 | 45 | |
| 3 | 50 | 2 |
| 4 | 38 | |
| 5 | 91 | 3 |
What the two counters mean
- 1PassCount increases only when the score is 50 or more.
- 2Tries increases for every input, including 45 and 38.
- 3The loop tests PassCount, then outputs Tries: the two counters have different jobs.
Watch the loop run, one line at a time
The trace shows the moment the goal is reached. Fill in one row from the lines that run.
| Line | Statement that runs | Tries | Score | PassCount | OUTPUT | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 4 | INPUT Score | 50 | Score 50 | the third score | |||
| the third score | |||||||
| 5 | Tries ← Tries + 1 | 3 | Tries 3 | 2 + 1: every input is an attempt | |||
| 2 + 1: every input is an attempt | |||||||
| 6 | IF Score >= 50 THEN | test 50 >= 50 is true, so line 7 runs | |||||
| test 50 >= 50 is true, so line 7 runs | |||||||
| 7 | PassCount ← PassCount + 1 | 2 | PassCount 2 | 1 + 1 | |||
| 1 + 1 | |||||||
| 9 | UNTIL PassCount = 3 | test 2 = 3 is false: repeat from line 4 | |||||
| test 2 = 3 is false: repeat from line 4 | |||||||
The whole run: one row each time round the loop
| Tries | Score | PassCount | OUTPUT | What decided it | |
|---|---|---|---|---|---|
| start | 0 | 0 | lines 1 and 2 set both counters to 0 | ||
| lines 1 and 2 set both counters to 0 | |||||
| pass 1 | 1 | 72 | 1 | 72 >= 50: PassCount 1; 1 = 3 is false: repeat | |
| 72 >= 50: PassCount 1; 1 = 3 is false: repeat | |||||
| pass 2 | 2 | 45 | 45 >= 50 is false: PassCount stays 1; 1 = 3 is false: repeat | ||
| 45 >= 50 is false: PassCount stays 1; 1 = 3 is false: repeat | |||||
| pass 3 | 3 | 50 | 2 | 50 >= 50: PassCount 2; 2 = 3 is false: repeat | |
| 50 >= 50: PassCount 2; 2 = 3 is false: repeat | |||||
| pass 4 | 4 | 38 | 38 >= 50 is false: PassCount stays 2; 2 = 3 is false: repeat | ||
| 38 >= 50 is false: PassCount stays 2; 2 = 3 is false: repeat | |||||
| pass 5 | 5 | 91 | 3 | 91 >= 50: PassCount 3; 3 = 3 is true: stop | |
| 91 >= 50: PassCount 3; 3 = 3 is true: stop | |||||
| end | 5 | line 10 outputs Tries: five attempts for three successes | |||
| line 10 outputs Tries: five attempts for three successes | |||||
Choose the loop from its stopping rule
Both loops repeat, but they stop for different reasons. The stopping rule tells you which loop to write.
| Loop | Condition tested | Choose it when… |
|---|---|---|
Count-controlledFOR … NEXT | the counter: runs from the start value to the end value | the number of iterations is known, e.g. read exactly five scores |
Conditional, pre-conditionWHILE … ENDWHILE | before the body; repeats while TRUE | the body may not need to run at all, or the loop can stop as soon as an item is found |
Conditional, post-conditionREPEAT … UNTIL | after the body; stops when TRUE | the body must run at least once, e.g. input a value and then check it |
What the two counters mean
- PassCount increases only when the score is 50 or more.
- Tries increases for every input, including 45 and 38.
- The loop tests PassCount, then outputs Tries: the stopping counter and output counter have different jobs.
1 The scores are 49, 80, 50, 51, 90. What does the target loop output?
2 Which loop would you choose to read exactly ten scores, and why?
3 Why does REPEAT … UNTIL suit the target loop?
- 14: the successes are 80, 50 and 51; the loop stops after the fourth input, so 90 is never read
- 2a count-controlled
FORloop: the number of iterations is known - 3a score must be input at least once before PassCount can be tested, and the number of attempts is not known in advance
Structured English and pseudocode
Structured English is full of “jump to step 7” and “repeat from step 2”, and pseudocode has no jumps. Translate one step at a time, then check the loop: what is repeated, and what makes it stop.
Structured English
1DECLARE Reading, Total, Days : INTEGER 2Total ← 0 3Days ← 0 4INPUT Reading 5WHILE Reading >= 0 6Total ← Total + Reading 7Days ← Days + 1 8INPUT Reading 9ENDWHILE 10OUTPUT Days, " days, total ", Total, " mm"
Phrases and their pseudocode
The same few phrases turn up again and again, and each has a standard translation.
| Structured English says… | Write in pseudocode |
|---|---|
| Set X to zero · add to X | X ← 0 before the loop · X ← X + 1 or X ← X + Value |
| Repeat steps 3 to 5 ten times | FOR Count ← 1 TO 10 … NEXT Count |
| Jump to step 7 if the reading is negative … repeat from step 2 | WHILE Reading >= 0, with INPUT before the loop and at its end; or REPEAT … UNTIL Reading < 0 with an IF so the last value is not processed |
Writing a structured English description
Sometimes the job runs the other way: describe an algorithm in plain English, with no pseudocode in it. The blue label on each step names its job.
Ages under 18, in steps
Rules
- Number the steps, one action in each.
- Name the loop and when it stops.
- Plain English: no
←,ENDIForDECLARE. - The value that ends the loop is not processed.
1 The readings are 5, 0, 9, −2, 4. What does the rainfall program output?
2 Write the pseudocode for “Repeat steps 2 to 3 four times”.
3 Write the steps for ages under 18 (ages until 0, count those under 18) as pseudocode.
- 1
3 days, total 14 mm: −2 ends the loop, so the 4 after it is never input - 2
FOR Count ← 1 TO 4…NEXT Count, around the statements for steps 2 and 3 - 3Answer
Count ← 0 REPEAT INPUT Age IF Age > 0 AND Age < 18 THEN Count ← Count + 1 ENDIF UNTIL Age = 0 OUTPUT Count
Writing pseudocode from a flowchart
A flowchart shows the paths; a program is written line by line. Each shape becomes a statement. A decision is a selection (paths join) or a loop (a path goes back up).
Tries ← 0 Connected ← FALSE WHILE Connected = FALSE AND Tries < 3 Tries ← Tries + 1 Connected ← TryConnect() ENDWHILE IF Connected = TRUE THEN OUTPUT "Ready" ELSE OUTPUT "Not connected" ENDIF
Tries ← 0 Connected ← FALSE REPEAT Tries ← Tries + 1 Connected ← TryConnect() UNTIL Connected = TRUE OR Tries >= 3 IF Connected = TRUE THEN OUTPUT "Ready" ELSE OUTPUT "Not connected" ENDIF
Both loops must make a first attempt because Tries starts at 0 and Connected at FALSE.
TryConnect() returns TRUE → 1 try, Ready; FALSE, TRUE → 2 tries, Ready; FALSE, FALSE, FALSE → 3 tries, Not connected.
TryConnect() returns | Tries | Output |
|---|---|---|
| TRUE | 1 | "Ready" |
| FALSE, TRUE | 2 | "Ready" |
| FALSE, FALSE, FALSE | 3 | "Not connected" |
Read the control paths
- A process box becomes an assignment; a subroutine box becomes CALL or a function call.
- A decision whose paths join again becomes IF … ELSE. A return above the test becomes WHILE.
- A test after the body, returning above the body, becomes REPEAT … UNTIL.
- A counter is set, tested and incremented for FOR; preserve any extra early-exit condition.
Read the flowchart shape by shape
Start at START and take one box at a time: each shape tells you which statement to write.
- 1Set Tries to 0, Set Connected to FALSE: process boxes become assignments,
Tries ← 0andConnected ← FALSE. - 2Set Connected to TryConnect(): a subroutine box becomes a function call,
Connected ← TryConnect()(orCALLfor a procedure). - 3Is Connected = FALSE AND Tries < 3 ?: its YES path goes back up above the test, so it becomes
WHILE, keeping both conditions. - 4Is Connected = TRUE ?: its two paths join again before END, so it becomes
IF … ELSE … ENDIF. - 5A test after the body that returns above the body becomes
REPEAT … UNTIL. A counter that is set, tested and incremented can becomeFOR.
1 TryConnect() returns FALSE, FALSE, TRUE. How many tries are made, and what is output?
2 Which flowchart shape becomes Connected ← TryConnect()?
3 The limit is changed to 5 tries. Write the new UNTIL condition for the post-condition loop.
- 13 tries, then
"Ready": the third call returns TRUE just before the limit - 2the subroutine box (a rectangle with double sides)
- 3
UNTIL Connected = TRUE OR Tries >= 5: the NOT ofConnected = FALSE AND Tries < 5
UNTIL gives the condition for stopping, so it is the NOT of the WHILE condition: NOT (Connected = FALSE AND Tries < 3) is Connected = TRUE OR Tries >= 3 (Tries = 3 also works here, as Tries never passes 3).Drawing a flowchart
Drawing a flowchart is the same translation run the other way, from steps to shapes. Turn each step into one shape and join the shapes with arrows. A “go to” or “repeat from” step becomes a flow line that returns to an earlier point.
Checklist for a flowchart
Each point matches a numbered circle on the flowchart.
- 1One START and one END, in terminator shapes.
- 2Initialise counts and totals before the loop.
- 3Every decision is a question with two labelled exits: YES / NO or TRUE / FALSE.
- 4The loop line returns above the step to be repeated, here the INPUT.
- 5Inputs and outputs go in parallelograms; use the identifiers you are given.
- 6Output after the loop if it happens once.
PassCount ← 0 FailCount ← 0 INPUT Mark WHILE Mark <> -1 IF Mark >= 40 THEN PassCount ← PassCount + 1 ELSE FailCount ← FailCount + 1 ENDIF INPUT Mark ENDWHILE OUTPUT "Passed: ", PassCount OUTPUT "Failed: ", FailCount
Marks 55, 38, 40, 72, 12, −1 → 3 passed, 2 failed. The flowchart repeats from the INPUT, so the pseudocode inputs before the loop and again at its end.
1 The marks input are 40, 39, −1. What does the flowchart output?
2 The loop line is drawn back to below the INPUT box instead. What goes wrong?
3 Which symbol holds Is Mark = -1 ?, and how are its exits labelled?
- 1
Passed: 1andFailed: 1: 40 >= 40 is a pass; −1 stops the loop and is not counted - 2no new mark is input: the same mark is tested again and again, so the loop never ends
- 3a decision diamond, with both exits labelled: YES and NO
Stepwise refinement
“Process each student” sounds like a plan until you try to code it: what is input, what is decided, what is output? Stepwise refinement breaks each step of an outline into smaller, more detailed steps, and repeats this until every step is precise enough to translate directly into code.
A first plan for a program is usually too vague to code. Stepwise refinement breaks each step of an outline into smaller, more detailed steps, and repeats this until every step is precise enough to translate directly into code.
Follow step 2: it splits into four smaller steps, and one of those, working out the grade, splits again.
Describe stepwise refinement in three moves
A good description has two parts: increase the level of detail, and keep going until each step can be programmed.
The finished steps become code one line at a time; the comment on each line names the step it came from.
CONSTANT ClassSize = 25 DECLARE Count, Mark, Total : INTEGER DECLARE Grade : CHAR Total ← 0 // step 1 FOR Count ← 1 TO ClassSize // step 2 INPUT Mark // 2.1 IF Mark >= 70 THEN // 2.2 Grade ← 'A' ELSE IF Mark >= 50 THEN Grade ← 'B' ELSE Grade ← 'C' ENDIF ENDIF OUTPUT Grade // 2.3 Total ← Total + Mark // 2.4 NEXT Count OUTPUT Total / ClassSize // 3.1, 3.2
Describe stepwise refinement
Increase the level of detail of the algorithm by breaking each step into smaller steps, until the steps can be directly translated into lines of code.
Is a step detailed enough?
- “Process the marks” is not: it hides an input, a decision, an output and a total.
- “Else if mark ≥ 50, grade is B” is: its condition and action are explicit.
Do not confuse
Decomposition splits a problem into sub-problems and modules. Stepwise refinement adds detail to the steps of one algorithm.
1 Which grade does step 2.2 give for marks of 50, 70 and 49?
2 Step 1 was not refined. Why not?
3 Is “Work out the grade” detailed enough to code? Say why.
- 150 → B, 70 → A, 49 → C: the tests are
>= 70, then>= 50 - 2it is already one assignment (
Total ← 0), so it can be coded directly - 3no: it hides a decision with two conditions, so it is refined into 2.2.1 to 2.2.3
Logic statements
Every IF and every conditional loop asks a question with a yes-or-no answer. That question is a logic statement: a condition that is TRUE or FALSE.
Every logic statement is built from the same few parts: six ways to compare two values, and three words that join or flip comparisons.
Relational operators
| Operator | Meaning |
|---|---|
= | equal to |
<> | not equal to |
< · <= | less than · less than or equal to |
> · >= | greater than · greater than or equal to |
Logic operators
| Operator | TRUE when… |
|---|---|
AND | both conditions are TRUE |
OR | at least one condition is TRUE |
NOT | the condition is FALSE |
AND and OR on a number line
A range condition is easier to judge as a picture. Blue marks the values that make it TRUE; a filled dot includes the limit, an open dot leaves it out.
From words to a logic statement
People say “over 12 and under 18”. Pseudocode needs a complete comparison on each side of AND or OR.
| In words | As a logic statement |
|---|---|
| Age is between 13 and 19 inclusive | (Age >= 13) AND (Age <= 19) |
| Temp is outside the range 18 to 24 | (Temp < 18) OR (Temp > 24) |
| Free entry for under-5s and for over-65s | (Age < 5) OR (Age > 65): one person cannot be both |
| Choice is 'Y' or 'y' | (Choice = 'Y') OR (Choice = 'y'), not Choice = 'Y' OR 'y' |
| Integer Month is outside the valid range | NOT ((Month >= 1) AND (Month <= 12)), the same as (Month < 1) OR (Month > 12) |
Evaluate each expression
Values: Age ← 15, Paid ← TRUE, Member ← FALSE, Score ← 72.
| Expression | Evaluates to |
|---|---|
Age >= 13 AND Age <= 19 | TRUE |
Paid AND NOT Member | TRUE |
NOT (Paid OR Member) | FALSE |
Score MOD 10 = 2 OR Age < 12 | TRUE |
NOT Paid OR (Score >= 70 AND Member) | FALSE |
Explain a logic statement
Alarm ← DoorOpen AND NOT Disarmed is TRUE only when the door is open and not disarmed.
Nested IFs as one condition
IF Paid THEN with IF NOT Member THEN inside it is one IF Paid AND NOT Member THEN.
1 Now Age ← 17, Paid ← FALSE, Member ← TRUE, Score ← 65. Evaluate (a) Age >= 13 AND Age <= 19, (b) Paid OR Member, (c) NOT Member AND Score > 60.
2 Write a logic statement that is TRUE when Size is from 1 to 10 inclusive.
3 Is (Temp < 18) OR (Temp > 24) TRUE when Temp is 24? Say why.
- 1(a) TRUE, (b) TRUE, (c) FALSE: in (c)
NOT Memberis FALSE, so AND gives FALSE - 2
(Size >= 1) AND (Size <= 10) - 3FALSE: 24 < 18 is FALSE and 24 > 24 is FALSE, so neither side is TRUE (the open dot on the number line)
Number = 3 OR 4 does not compare Number with 4. For “between … inclusive” use >= and <=, and add brackets to make the order of evaluation clear.Selection with ranges and bands
A shop charges less for delivery the more you spend: 4.99 below 20, 2.99 from 20 to 50 inclusive, and nothing above 50. When a value falls into one of several bands, the tests and their order decide which band is chosen.
Follow a value of 25 through the decisions: the first answers NO and hands it on, the second answers YES, so the charge is 2.99.
INPUT Value IF Value < 20 THEN Charge ← 4.99 ELSE IF Value <= 50 THEN Charge ← 2.99 ELSE Charge ← 0.00 ENDIF ENDIF OUTPUT Charge
Test the boundaries
| Value | Band | Charge |
|---|---|---|
| 19.99 | below 20 | 4.99 |
| 20.00 | 20 to 50 | 2.99 |
| 50.00 | 20 to 50 | 2.99 |
| 50.01 | above 50 | 0.00 |
The values either side of each limit show whether < or <= is right. Declaring the limits as constants (CONSTANT LowLimit = 20) means a change is made in one place.
When the order or structure is wrong
A band algorithm can look right and still charge the wrong amount. Find the error, then say how to correct it.
IF Value < 20 THEN Charge ← 4.99 ENDIF IF Value <= 50 THEN Charge ← 2.99 ENDIF
Do not confuse
- Separate IFs: a value of 10 passes both tests, so
Chargeends as 2.99, not 4.99. - Wrong order: if
Value <= 50is tested first, 10 also gets 2.99, andValue < 20under its ELSE can never be TRUE. - Correct it: nest the IFs, and swap the two decisions.
1 What does the nested IF output for a value of 35? And for 75?
2 Which two values test the limit at 50?
3 Write the middle band (20 to 50 inclusive) as one logic statement.
- 135 → 2.99, 75 → 0.00
- 250.00 (the highest value charged 2.99) and 50.01 (the lowest value that is free)
- 3
(Value >= 20) AND (Value <= 50)
Totalling, counting and averages
A program reads values one at a time and cannot look back, so it keeps score as it goes. Totalling adds each value to a running total: Total ← Total + Value. Counting adds 1 each time: Count ← Count + 1. Both start at zero before the loop; the mean is worked out after it.
1DECLARE Count, Minutes : INTEGER 2DECLARE Total, LongCount : INTEGER 3Total ← 0 4LongCount ← 0 5FOR Count ← 1 TO 6 6INPUT Minutes 7Total ← Total + Minutes 8IF Minutes >= 30 THEN 9LongCount ← LongCount + 1 10ENDIF 11NEXT Count 12OUTPUT "Total: ", Total 13OUTPUT "30 or more: ", LongCount 14OUTPUT "Mean: ", Total / 6
Trace with 25, 40, 30, 15, 50, 23
Count | Minutes | Total | LongCount | OUTPUT |
|---|---|---|---|---|
| 0 | 0 | |||
| 1 | 25 | 25 | ||
| 2 | 40 | 65 | 1 | |
| 3 | 30 | 95 | 2 | |
| 4 | 15 | 110 | ||
| 5 | 50 | 160 | 3 | |
| 6 | 23 | 183 | ||
| Total: 183 | ||||
| 30 or more: 3 | ||||
| Mean: 30.5 |
Four places, four jobs
- 1Before the loop (lines 3–4): set Total and LongCount to 0.
- 2Inside the loop (lines 6–9): input, add to the total, test and count.
- 3After the loop (lines 12–14): output the results once.
- 4Mean = Total ÷ the number of values added: 183 ÷ 6 = 30.5.
Watch the loop run, one line at a time
Total changes on every pass; the count changes only when the test is TRUE. Fill in a row in that order.
| Line | Statement that runs | Count | Minutes | Total | LongCount | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 5 | FOR Count ← 1 TO 6 | 2 | Count 2 | the next value of Count | |||
| the next value of Count | |||||||
| 6 | INPUT Minutes | 40 | Minutes 40 | the second input | |||
| the second input | |||||||
| 7 | Total ← Total + Minutes | 65 | Total 65 | 25 + 40 | |||
| 25 + 40 | |||||||
| 8 | IF Minutes >= 30 THEN | test 40 >= 30 is true, so line 9 runs | |||||
| test 40 >= 30 is true, so line 9 runs | |||||||
| 9 | LongCount ← LongCount + 1 | 1 | LongCount 1 | 0 + 1 | |||
| 0 + 1 | |||||||
| 11 | NEXT Count | test back to line 5 for Count 3 | |||||
| test back to line 5 for Count 3 | |||||||
The whole run: one row each time round the loop
| Count | Minutes | Total | LongCount | What decided it | |
|---|---|---|---|---|---|
| start | 0 | 0 | lines 3 and 4 set Total and LongCount to 0 | ||
| lines 3 and 4 set Total and LongCount to 0 | |||||
| pass 1 | 1 | 25 | 25 | 0 + 25 = 25; 25 >= 30 is false: LongCount is left blank | |
| 0 + 25 = 25; 25 >= 30 is false: LongCount is left blank | |||||
| pass 2 | 2 | 40 | 65 | 1 | 25 + 40 = 65; 40 >= 30: LongCount 1 |
| 25 + 40 = 65; 40 >= 30: LongCount 1 | |||||
| pass 3 | 3 | 30 | 95 | 2 | 65 + 30 = 95; 30 >= 30: LongCount 2 |
| 65 + 30 = 95; 30 >= 30: LongCount 2 | |||||
| pass 4 | 4 | 15 | 110 | 95 + 15 = 110; 15 >= 30 is false: LongCount is left blank | |
| 95 + 15 = 110; 15 >= 30 is false: LongCount is left blank | |||||
| pass 5 | 5 | 50 | 160 | 3 | 110 + 50 = 160; 50 >= 30: LongCount 3 |
| 110 + 50 = 160; 50 >= 30: LongCount 3 | |||||
| pass 6 | 6 | 23 | 183 | 160 + 23 = 183; 23 >= 30 is false: LongCount is left blank | |
| 160 + 23 = 183; 23 >= 30 is false: LongCount is left blank | |||||
| end | after the loop, lines 12–14 output once: Total: 183, 30 or more: 3, Mean: 30.5 (183 ÷ 6 = 30.5) | ||||
after the loop, lines 12–14 output once: Total: 183, 30 or more: 3, Mean: 30.5 (183 ÷ 6 = 30.5) | |||||
To average only some of the values, keep a second total for just those, and divide by how many there were.
LongTotal ← 0 LongCount ← 0 FOR Count ← 1 TO 6 INPUT Minutes IF Minutes >= 30 THEN LongTotal ← LongTotal + Minutes LongCount ← LongCount + 1 ENDIF NEXT Count IF LongCount > 0 THEN OUTPUT LongTotal / LongCount ELSE OUTPUT "None of 30 or more" ENDIF
Diagnose wrong totals and means
Total ← 0inside the loop resets the total on every pass.- Dividing the selected total by all the inputs: 120 ÷ 6 = 20, not 40.
- Using
DIVfor a mean loses the fraction: 183 DIV 6 = 30, not 30.5. - An
OUTPUTinside the loop prints a running value after every input. - If the selected count can be 0, check it before dividing.
1 The inputs are 30, 10, 45, 20, 35, 40. What are the three outputs?
2 Total ← 0 is moved inside the loop, just after INPUT Minutes. With the inputs 25, 40, 30, 15, 50, 23, what Total is output?
3 Run the mean of the selected values program on 30, 10, 45, 20, 35, 40. What is output?
- 1
Total: 180,30 or more: 4,Mean: 30.0 - 223: the total is reset on every pass, so only the last input is left
- 337.5: 30 + 45 + 35 + 40 = 150, ÷ 4 values
Maximum and minimum
To find the coldest day of a week by eye, you remember the coldest so far and compare each new day with it. A program finds the maximum or minimum the same way: it keeps the best value found so far. It starts from the first value input, then loops through the rest.
1DECLARE Day, Temp, ColdDay : INTEGER 2DECLARE Highest, Lowest : INTEGER 3INPUT Temp 4Highest ← Temp 5Lowest ← Temp 6ColdDay ← 1 7FOR Day ← 2 TO 7 8INPUT Temp 9IF Temp > Highest THEN 10Highest ← Temp 11ENDIF 12IF Temp < Lowest THEN 13Lowest ← Temp 14ColdDay ← Day 15ENDIF 16NEXT Day 17OUTPUT "Highest: ", Highest 18OUTPUT "Lowest: ", Lowest 19OUTPUT "Coldest day: ", ColdDay
Trace with −2, −9, 1, −4, −9, −3, 0
Day | Temp | Highest | Lowest | ColdDay |
|---|---|---|---|---|
| -2 | -2 | -2 | 1 | |
| 2 | -9 | -9 | 2 | |
| 3 | 1 | 1 | ||
| 4 | -4 | |||
| 5 | -9 | |||
| 6 | -3 | |||
| 7 | 0 |
Output: Highest: 1, Lowest: -9, Coldest day: 2.
Inputs −2, −9, 1, −4, −9, −3, 0
- 1Start from the first input (lines 3–6): Highest and Lowest are both −2.
- 2Loop through the other six (line 7): compare each with the best so far.
- 3Replace only when the new value is greater (or smaller). ColdDay records the day.
- 4Output after the loop:
Highest: 1,Lowest: -9,Coldest day: 2.
Watch the loop run, one line at a time
On most days nothing changes. A value is written only when a test is TRUE and the new temperature replaces the old one.
| Line | Statement that runs | Day | Temp | Highest | Lowest | ColdDay | Writes | What happens |
|---|---|---|---|---|---|---|---|---|
| 7 | FOR Day ← 2 TO 7 | 2 | Day 2 | the loop starts at the second day | ||||
| the loop starts at the second day | ||||||||
| 8 | INPUT Temp | -9 | Temp -9 | the second input | ||||
| the second input | ||||||||
| 9 | IF Temp > Highest THEN | test −9 > −2 is false: line 10 is skipped | ||||||
| test −9 > −2 is false: line 10 is skipped | ||||||||
| 12 | IF Temp < Lowest THEN | test −9 < −2 is true | ||||||
| test −9 < −2 is true | ||||||||
| 13 | Lowest ← Temp | -9 | Lowest -9 | the new lowest | ||||
| the new lowest | ||||||||
| 14 | ColdDay ← Day | 2 | ColdDay 2 | remember where it was found | ||||
| remember where it was found | ||||||||
The whole run: one row each day
| Day | Temp | Highest | Lowest | ColdDay | What decided it | |
|---|---|---|---|---|---|---|
| start | -2 | -2 | -2 | 1 | lines 3–6: the first input starts Highest and Lowest; ColdDay 1 | |
| lines 3–6: the first input starts Highest and Lowest; ColdDay 1 | ||||||
| day 2 | 2 | -9 | -9 | 2 | new lowest −9: ColdDay 2 | |
| new lowest −9: ColdDay 2 | ||||||
| day 3 | 3 | 1 | 1 | new highest 1 | ||
| new highest 1 | ||||||
| day 4 | 4 | -4 | neither test is TRUE: nothing changes | |||
| neither test is TRUE: nothing changes | ||||||
| day 5 | 5 | -9 | −9 = −9 is not lower: the first −9 is kept | |||
| −9 = −9 is not lower: the first −9 is kept | ||||||
| day 6 | 6 | -3 | neither test is TRUE: nothing changes | |||
| neither test is TRUE: nothing changes | ||||||
| day 7 | 7 | 0 | neither test is TRUE: nothing changes | |||
| neither test is TRUE: nothing changes | ||||||
Three small choices change the answer: the starting value, the test, and which value is left out of a mean.
Start from the first value
If Highest started at 0, a week from −9 to −2 would output 0, a value never input.
< or <=?
With < the first −9 is kept: day 2. With <= the later −9 replaces it: day 5.
Mean without the highest
Subtract the highest from the total and divide by one fewer: (−26 − 1) ÷ 6 = −4.5.
Structured English: finding the highest
1 The temperatures are 3, 7, −1, 7, 2, −1, 5. What are the three outputs?
2 Line 12 is changed to IF Temp <= Lowest THEN. What is the coldest day now?
3 Why must Highest start from the first input, not from 0?
- 1
Highest: 7,Lowest: −1,Coldest day: 3: the first −1 is on day 3 - 2day 6: with
<=the later −1 replaces the first one - 3if every input is below 0, a start of 0 would be output, a value that was never input
Rogue values: ending a sequence of inputs
When nobody knows how many parcels will be weighed, the program needs a signal that the inputs have ended. A rogue value (sentinel) marks the end of a sequence of inputs. It has the same data type as the data but is reserved and excluded from valid data: for positive parcel weights, 0 kg is the stop signal.
A rogue value (sentinel) marks the end of a sequence of inputs. It has the same data type as the data but is reserved and excluded from valid data: for positive parcel weights, 0 kg is the stop signal.
1DECLARE Weight, Total : REAL 2DECLARE Count : INTEGER 3Total ← 0.0 4Count ← 0 5INPUT Weight 6WHILE Weight <> 0.0 7Total ← Total + Weight 8Count ← Count + 1 9INPUT Weight 10ENDWHILE 11IF Count > 0 THEN 12OUTPUT "Mean: ", Total / Count 13ELSE 14OUTPUT "No parcels" 15ENDIF
Trace with 2.5, 4.0, 1.5, 4.0, 0.0
Weight | Total | Count | OUTPUT |
|---|---|---|---|
| 2.5 | 0.0 | 0 | |
| 4.0 | 2.5 | 1 | |
| 1.5 | 6.5 | 2 | |
| 4.0 | 8.0 | 3 | |
| 0.0 | 12.0 | 4 | |
| Mean: 3.0 |
Each row is just after INPUT: Total and Count describe values already processed. The newly read value is tested before processing.
Where the rogue value is handled
- 1Read before the loop (line 5), so the first value can be tested.
- 2Test before processing (line 6): 0.0 stops the loop.
- 3Process, then read the next (lines 7–9).
- 4Check the count (line 11) before dividing.
Watch the loop run, one line at a time
The rogue value must never be added in. That is why the value just read is tested before it is added.
| Line | Statement that runs | Weight | Total | Count | OUTPUT | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 6 | WHILE Weight <> 0.0 | test 4.0 <> 0.0 is true, so the body runs | |||||
| test 4.0 <> 0.0 is true, so the body runs | |||||||
| 7 | Total ← Total + Weight | 6.5 | Total 6.5 | 2.5 + 4.0 | |||
| 2.5 + 4.0 | |||||||
| 8 | Count ← Count + 1 | 2 | Count 2 | 1 + 1 | |||
| 1 + 1 | |||||||
| 9 | INPUT Weight | 1.5 | Weight 1.5 | read the next weight at the end of the body | |||
| read the next weight at the end of the body | |||||||
| 6 | WHILE Weight <> 0.0 | test back to the test with 1.5 | |||||
| test back to the test with 1.5 | |||||||
The whole run: one row each time round the loop
| Weight | Total | Count | OUTPUT | What decided it | |
|---|---|---|---|---|---|
| start | 2.5 | 0.0 | 0 | lines 3–5: the first weight is read before the loop | |
| lines 3–5: the first weight is read before the loop | |||||
| pass 1 | 4.0 | 2.5 | 1 | 2.5 <> 0.0 is true: add 2.5, count it, read the next weight | |
| 2.5 <> 0.0 is true: add 2.5, count it, read the next weight | |||||
| pass 2 | 1.5 | 6.5 | 2 | 4.0 <> 0.0 is true: add 4.0, count it, read the next weight | |
| 4.0 <> 0.0 is true: add 4.0, count it, read the next weight | |||||
| pass 3 | 4.0 | 8.0 | 3 | 1.5 <> 0.0 is true: add 1.5, count it, read the next weight | |
| 1.5 <> 0.0 is true: add 1.5, count it, read the next weight | |||||
| pass 4 | 0.0 | 12.0 | 4 | 4.0 <> 0.0 is true: add 4.0, count it, read the next weight | |
| 4.0 <> 0.0 is true: add 4.0, count it, read the next weight | |||||
| end | Mean: 3.0 | 0.0 <> 0.0 is false: the loop ends and 0.0 is never added; Count > 0, so line 12 outputs 12.0 ÷ 4 | |||
| 0.0 <> 0.0 is false: the loop ends and 0.0 is never added; Count > 0, so line 12 outputs 12.0 ÷ 4 | |||||
A REPEAT loop runs its body before any test, so it needs an IF inside to keep the rogue value out of the total.
REPEAT INPUT Weight IF Weight <> 0.0 THEN Total ← Total + Weight Count ← Count + 1 ENDIF UNTIL Weight = 0.0
Do not process the rogue value
Without the IF, the 0.0 would be counted: Count = 5 and the output Mean: 2.4 instead of Mean: 3.0.
If the first input is 0.0, the WHILE body runs zero times, so check Count > 0 before dividing: the output is No parcels.
Choosing a rogue value
A stop signal only works if it can never be a real value, so the right choice depends on the data.
| Data | Valid values | A suitable rogue value |
|---|---|---|
| parcel weights in kg | greater than 0 | 0.0: no parcel weighs 0 kg |
| exam marks | 0 to 100 | -1: below the lowest possible mark |
| product codes (STRING) | four digits | "END": not a valid code |
| temperatures in °C | use the task’s range; 0 and negative values can be valid | 999 only if reserved outside that range; otherwise input the count first |
1 The weights input are 3.5, 1.0, 0.0. What is output?
2 The first weight input is 0.0. What is output, and why?
3 Ages of club members are from 0 to 120. Suggest a rogue value and give a reason.
- 1
Mean: 2.25: (3.5 + 1.0) ÷ 2 = 2.25 - 2
No parcels: the WHILE test is FALSE at once, so Count stays 0 and the IF stops a division by 0 - 3for example −1: it is an integer like the ages, but no member can be −1 years old
Input validation loops
A mark of 105, typed by mistake, would quietly spoil every average worked out from it. An input validation loop keeps asking until the value meets the rule; its condition is a logic statement that describes a valid (or an invalid) value.
A mark of 105 must never reach the records. An input validation loop repeats the input until the value meets the rule. The loop condition is a logic statement that describes a valid (or an invalid) value.
Two ways to keep asking: REPEAT asks first and tests afterwards; WHILE tests first, then asks again with an error message.
REPEAT OUTPUT "Enter a mark from 0 to 100" INPUT Mark UNTIL Mark >= 0 AND Mark <= 100
1OUTPUT "Enter a mark from 0 to 100" 2INPUT Mark 3WHILE Mark < 0 OR Mark > 100 4OUTPUT "Invalid: re-enter the mark" 5INPUT Mark 6ENDWHILE
Trace of the pre-condition loop with 105, −3, 67
Mark | Mark < 0 OR Mark > 100 | OUTPUT |
|---|---|---|
| Enter a mark from 0 to 100 | ||
| 105 | TRUE | Invalid: re-enter the mark |
| -3 | TRUE | Invalid: re-enter the mark |
| 67 | FALSE |
67 makes the condition FALSE, so the loop ends and 67 is accepted.
Trace the pre-condition loop with 105, −3, 67
For each input, decide whether the condition is TRUE: that tells you whether the loop asks again or moves on.
| Line | Statement that runs | Mark | OUTPUT | Writes | What happens |
|---|---|---|---|---|---|
| 3 | WHILE Mark < 0 OR Mark > 100 | test 105 < 0 is FALSE, 105 > 100 is TRUE: FALSE OR TRUE is TRUE, so the body runs | |||
| test 105 < 0 is FALSE, 105 > 100 is TRUE: FALSE OR TRUE is TRUE, so the body runs | |||||
| 4 | OUTPUT "Invalid: re-enter the mark" | Invalid: re-enter the mark | OUTPUT Invalid: re-enter the mark | say what was wrong | |
| say what was wrong | |||||
| 5 | INPUT Mark | -3 | Mark -3 | a new value replaces the invalid one | |
| a new value replaces the invalid one | |||||
| 3 | WHILE Mark < 0 OR Mark > 100 | test back to the test with −3 | |||
| test back to the test with −3 | |||||
The whole run: one row each time round the loop
| Mark | OUTPUT | What decided it | |
|---|---|---|---|
| start | 105 | Enter a mark from 0 to 100 | lines 1–2: prompt, then the first input |
| lines 1–2: prompt, then the first input | |||
| pass 1 | -3 | Invalid: re-enter the mark | 105 > 100, so the condition is TRUE: error message, input again |
| 105 > 100, so the condition is TRUE: error message, input again | |||
| pass 2 | 67 | Invalid: re-enter the mark | −3 < 0, so the condition is TRUE: error message, input again |
| −3 < 0, so the condition is TRUE: error message, input again | |||
| end | 67: both comparisons are FALSE, so the loop ends and 67 is accepted | ||
| 67: both comparisons are FALSE, so the loop ends and 67 is accepted | |||
NOT (Mark >= 0 AND Mark <= 100) is Mark < 0 OR Mark > 100.Checks written as logic statements
Length, presence and type checks all end up as the condition of a loop, written for a valid or for an invalid value.
| Check | The input is valid when… |
|---|---|
| Length | LENGTH(Code) = 6 |
| Length range | Valid: (LENGTH(Code) >= 4) AND (LENGTH(Code) <= 6); invalid: (LENGTH(Code) < 4) OR (LENGTH(Code) > 6) |
| Presence | Name <> "" |
| Whole number | Value = INT(Value) |
| Odd number | Size MOD 2 = 1 |
Tries ← 0 REPEAT INPUT Guess Tries ← Tries + 1 UNTIL Guess = 4071 OR Tries = 3 IF Guess = 4071 THEN OUTPUT "Unlocked" ELSE OUTPUT "Locked" ENDIF
1 The REPEAT version is given 101, 100. How many times is the prompt output, and which mark is accepted?
2 Write a REPEAT … UNTIL loop that inputs Size until it is an odd number.
3 The guesses for the PIN loop are 1111, 2222, 3333. What is output?
- 1the prompt is output 2 times; 100 is accepted:
100 <= 100is TRUE - 2Answer
REPEAT INPUT Size UNTIL Size MOD 2 = 1
- 3
"Locked": three wrong guesses makeTries = 3, so the loop stops
Tracing an algorithm
The surest way to find out what an algorithm really does is to be the computer for a while. A dry run follows an algorithm by hand; a trace table records each new value and every output.
1INPUT Number 2Total ← 0 3Count ← 0 4WHILE Number > 0 5Digit ← Number MOD 10 6Total ← Total + Digit 7IF Digit > 4 THEN 8Count ← Count + 1 9ENDIF 10Number ← Number DIV 10 11ENDWHILE 12OUTPUT Total, " ", Count
Trace with input 3725
Number | Digit | Total | Count | OUTPUT |
|---|---|---|---|---|
| 3725 | 0 | 0 | ||
| 372 | 5 | 5 | 1 | |
| 37 | 2 | 7 | ||
| 3 | 7 | 14 | 2 | |
| 0 | 3 | 17 | ||
| 17 2 |
Rules for a trace table
- 1Follow the statements in the order they run, not the order they are written.
- 2Write a value only when a line changes it; a blank means no change.
- 3Record OUTPUT when the OUTPUT statement runs, exactly as output.
- 4Check the loop test again before running another pass.
Read the first iteration
3725 MOD 10 gives Digit 5. Total becomes 5 and Count becomes 1 because 5 > 4. 3725 DIV 10 then makes Number 372. The next iteration takes the new final digit, 2. Here each row is a snapshot after the whole loop body, so it shows Number after DIV.
Watch the loop run, one line at a time
Once there is a loop, lines no longer run in the order they are written. Follow them as they run and write each new value in its column.
| Line | Statement that runs | Number | Digit | Total | Count | OUTPUT | Writes | What happens |
|---|---|---|---|---|---|---|---|---|
| 4 | WHILE Number > 0 | test 3725 > 0 is true, so the body runs | ||||||
| test 3725 > 0 is true, so the body runs | ||||||||
| 5 | Digit ← Number MOD 10 | 5 | Digit 5 | 3725 MOD 10: the last digit | ||||
| 3725 MOD 10: the last digit | ||||||||
| 6 | Total ← Total + Digit | 5 | Total 5 | 0 + 5 | ||||
| 0 + 5 | ||||||||
| 7 | IF Digit > 4 THEN | test 5 > 4 is true, so line 8 runs | ||||||
| test 5 > 4 is true, so line 8 runs | ||||||||
| 8 | Count ← Count + 1 | 1 | Count 1 | 0 + 1 | ||||
| 0 + 1 | ||||||||
| 10 | Number ← Number DIV 10 | 372 | Number 372 | 3725 DIV 10: the last digit is removed | ||||
| 3725 DIV 10: the last digit is removed | ||||||||
The whole run: one row each time round the loop
| Number | Digit | Total | Count | OUTPUT | What decided it | |
|---|---|---|---|---|---|---|
| start | 3725 | 0 | 0 | lines 1–3: input 3725; Total and Count start at 0 | ||
| lines 1–3: input 3725; Total and Count start at 0 | ||||||
| pass 1 | 372 | 5 | 5 | 1 | 3725 MOD 10 = 5; 5 > 4: Count 1; 3725 DIV 10 = 372 | |
| 3725 MOD 10 = 5; 5 > 4: Count 1; 3725 DIV 10 = 372 | ||||||
| pass 2 | 37 | 2 | 7 | 372 MOD 10 = 2; 2 > 4 is false; 372 DIV 10 = 37 | ||
| 372 MOD 10 = 2; 2 > 4 is false; 372 DIV 10 = 37 | ||||||
| pass 3 | 3 | 7 | 14 | 2 | 37 MOD 10 = 7; 7 > 4: Count 2; 37 DIV 10 = 3 | |
| 37 MOD 10 = 7; 7 > 4: Count 2; 37 DIV 10 = 3 | ||||||
| pass 4 | 0 | 3 | 17 | 3 MOD 10 = 3; 3 > 4 is false; 3 DIV 10 = 0 | ||
| 3 MOD 10 = 3; 3 > 4 is false; 3 DIV 10 = 0 | ||||||
| end | 17 2 | 0 > 0 is false: the loop ends and line 12 runs | ||||
| 0 > 0 is false: the loop ends and line 12 runs | ||||||
Rules for a trace table
- Follow the statements in the order they run, not the order they are written.
- Follow any trace instructions you are given. These snapshots show assignments in each executed loop body; a blank means no update.
- Record OUTPUT when the OUTPUT statement runs, exactly as output.
- Check the final loop test before executing another body.
Walkthrough testing
A dry run is also a test: it shows the point where an algorithm stops doing what was intended.
- 1Choose inputs and the expected results.
- 2Follow each statement in a trace table.
- 3Compare the actual values and paths with the expected ones: a difference locates a logic error. (With separate IFs for the delivery bands, Value 10 sets Charge to 4.99, then overwrites it with 2.99.)
1 Trace the algorithm with input 408. What is output?
2 How many times does the loop body run for 50020?
3 Which input makes the loop body run zero times?
- 1
12 1: digits 8, 0, 4 give Total 12; only 8 is more than 4 - 25 times, once for each digit (Number becomes 5002, 500, 50, 5, 0)
- 3
0(or any value not above 0):WHILE Number > 0is FALSE at the first test
Tracing nested loops
A loop inside another loop is easy to misread, because each outer-loop value starts a fresh inner loop. Here Inner runs from 1 to Outer: one addition, then two, then three. Total accumulates across all six additions.
1Total ← 0 2FOR Outer ← 1 TO 3 3FOR Inner ← 1 TO Outer 4Total ← Total + Inner 5NEXT Inner 6NEXT Outer 7OUTPUT Total
Snapshots after Total is updated
Outer | Inner | Total | OUTPUT |
|---|---|---|---|
| 0 | |||
| 1 | 1 | 1 | |
| 2 | 1 | 2 | |
| 2 | 4 | ||
| 3 | 1 | 5 | |
| 2 | 7 | ||
| 3 | 10 | ||
| 10 |
Two loops, one total
- 1Line 1 sets Total to 0 once, before both loops.
- 2Line 3 starts Inner at 1 again for every value of Outer.
- 3Line 4 runs 1 + 2 + 3 = 6 times in all.
- 4Line 7 runs once, after both loops: Total is 10.
Watch the loops run, one line at a time
The usual mistake is resetting the wrong thing. Watch where the inner loop restarts and where the total carries on.
| Line | Statement that runs | Outer | Inner | Total | OUTPUT | Writes | What happens |
|---|---|---|---|---|---|---|---|
| 2 | FOR Outer ← 1 TO 3 | 2 | Outer 2 | the next value of Outer | |||
| the next value of Outer | |||||||
| 3 | FOR Inner ← 1 TO Outer | 1 | Inner 1 | Inner starts again at 1; it will run to 2 | |||
| Inner starts again at 1; it will run to 2 | |||||||
| 4 | Total ← Total + Inner | 2 | Total 2 | 1 + 1 | |||
| 1 + 1 | |||||||
| 5 | NEXT Inner | 2 | Inner 2 | 2 <= 2: run the body again | |||
| 2 <= 2: run the body again | |||||||
| 4 | Total ← Total + Inner | 4 | Total 4 | 2 + 2 | |||
| 2 + 2 | |||||||
| 5 | NEXT Inner | test Inner would be 3, and 3 > 2: the inner loop ends | |||||
| test Inner would be 3, and 3 > 2: the inner loop ends | |||||||
| 6 | NEXT Outer | test back to line 2 for Outer 3 | |||||
| test back to line 2 for Outer 3 | |||||||
The whole run: one row for each addition
| Outer | Inner | Total | OUTPUT | What decided it | |
|---|---|---|---|---|---|
| start | 0 | line 1: Total is set to 0 once, before both loops | |||
| line 1: Total is set to 0 once, before both loops | |||||
| add 1 | 1 | 1 | 1 | Outer 1 starts a fresh inner loop: Inner 1; 0 + 1 = 1 | |
| Outer 1 starts a fresh inner loop: Inner 1; 0 + 1 = 1 | |||||
| add 2 | 2 | 1 | 2 | Outer 2 starts a fresh inner loop: Inner 1; 1 + 1 = 2 | |
| Outer 2 starts a fresh inner loop: Inner 1; 1 + 1 = 2 | |||||
| add 3 | 2 | 4 | Inner 2 <= 2: 2 + 2 = 4 | ||
| Inner 2 <= 2: 2 + 2 = 4 | |||||
| add 4 | 3 | 1 | 5 | Outer 3 starts a fresh inner loop: Inner 1; 4 + 1 = 5 | |
| Outer 3 starts a fresh inner loop: Inner 1; 4 + 1 = 5 | |||||
| add 5 | 2 | 7 | Inner 2 <= 3: 5 + 2 = 7 | ||
| Inner 2 <= 3: 5 + 2 = 7 | |||||
| add 6 | 3 | 10 | Inner 3 <= 3: 7 + 3 = 10 | ||
| Inner 3 <= 3: 7 + 3 = 10 | |||||
| end | 10 | Outer has passed 3: both loops are finished; line 7 outputs Total | |||
| Outer has passed 3: both loops are finished; line 7 outputs Total | |||||
Two loop returns: Inner repeats inside Outer
In the flowchart each loop has its own return line: the inner one goes back above its own test, the outer one above the outer test.
Reset the inner counter, preserve the total
1 The outer loop is changed to FOR Outer ← 1 TO 4. What is output?
2 How many times does line 4 run now?
3 Back to 1 TO 3: Total ← 0 is moved to just inside the outer loop. What is output?
- 120: the old 10, plus 1 + 2 + 3 + 4 for Outer 4
- 210 times: 1 + 2 + 3 + 4
- 36: Total is reset for each Outer, so only the last pass (1 + 2 + 3) is left