Skip to content

9618 · Unit 9 · Paper 2: Problem-solving and programming

Algorithm design and problem-solving.

9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Abstraction: keep only what the task needs

§9.1 · Computational thinking skills · abstraction

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.

Data stored about each memberNeeded for this task?Abstract model for the reminder taskMember IDNameHome address×not usedDate of birth×not usedMobile numberEmail address×not usedExpiry dateSwimming level×not usedMember IDidentifies the member's recordNamepersonalises the messageMobile numberwhere the text is sentExpiry dateselects who gets a reminder
Stored dataTask's abstract modelMember IDMember IDidentifies the member'srecordNameNamepersonalises the messageHome addressNot needed for this taskDate of birthNot needed for this taskMobile numberMobile numberwhere the text is sentEmail addressNot needed for this taskExpiry dateExpiry dateselects who gets areminderSwimming levelNot needed for this taskKeep the data each required operation uses.
Filtering unneeded facts simplifies the solution and tailors it to users' needs. What is essential depends on the task: for lane placement, Swimming level is essential and Mobile number is not.

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 neededReason
Home addressthe text is sent to a phone, not posted
Date of birthage does not decide this expiry reminder
Email addressthe channel is SMS
Swimming levellane placement is a different task
Your turn

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.

  1. 1
    Home address becomes essential (the letter must be addressed); Mobile number is no longer needed
  2. 2
    information that is not necessary for the task: only the essential details are kept
  3. 3
    the solution is simpler to design and program, and it is tailored to what the users need
Tick what you can do now
Exam focusGive each item with a justification from the scenario: “mobile number, to send the text message”. An item is not essential just because it is stored. For the purpose, write filter out information that is not necessary (or keep only the essential information) for the task.
Practise with s24/21 Q7(a)(ii); w24/22 Q7(a); s26/22 Q2(a), (c)
1 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Decomposition: from a problem to modules

§9.1 · Computational thinking skills · decomposition

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.

ProblemSub-problemsProgram modulesRenew a membershiponlineIdentify the memberFindMember(MemberID)function · returns TRUE if foundWork out the renewal feeCalculateFee(Level, Months)function · returns the feeTake the paymentTakePayment(Fee)function · returns TRUE if paidUpdate the expiry dateUpdateExpiry(MemberID, Months)procedureConfirm the renewalSendConfirmation(MemberID)procedure
Renew a membership onlineIdentify the memberFindMember(MemberID)function · returns TRUE if foundWork out the renewal feeCalculateFee(Level, Months)function · returns the feeTake the paymentTakePayment(Fee)function · returns TRUE if paidUpdate the expiry dateUpdateExpiry(MemberID, Months)procedureConfirm the renewalSendConfirmation(MemberID)procedureBranches show the problem's separate sub-problems.

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.

1Break the problem down
Split it into sub-problems, such as identifying the member and working out the fee.
passes onsub-problems
2Explain each part
Describe each sub-problem in more detail, so it is easier to understand and solve.
passes onsmall, separate parts
3Make each a module
Design and write each part as a program module, separately.
resultprocedures and functions
1
Break the problem down into sub-problems, such as identifying the member and working out the fee.
2
This explains the process in more detail, so each part is easier to understand and solve.
3
Each sub-problem leads to a program module (procedure or function), designed and written separately.

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.

ProcedureFunction
What it doescarries out a taskcarries out a task and returns a single value
How it is calledas 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.
Your turn

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. 1
    SendConfirmation: it is a procedure, so it returns no value. TakePayment is a function: it returns TRUE if paid, so it is used in an expression
  2. 2
    Answer
    Fee ← CalculateFee("Senior", 6)
    
  3. 3
    for example: take the order, work out the bill, send the order to the kitchen, take the payment
Tick what you can do now
Exam focusDescribe decomposition in the context of the question: name sub-problems from the scenario. A generic phrase alone does not show how the task is divided. For a module, give a name and its use: CalculateFee() works out the renewal fee.
Practise with s25/21 Q1(c); s24/22 Q7(a); w24/23 Q7(b); w24/21 Q4(b)
2 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Algorithms, identifiers and identifier tables

§9.2 · Algorithms · input, process, output

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.

Pseudocode
 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
INPUTPROCESSOUTPUTStudents ← 100Coaches ← 100 DIV 45 = 2100 MOD 45 = 10, not 0, so add 1Coaches = 3EmptySeats ← 3 × 45 − 100 = 35Coaches needed: 3Empty seats: 35
INPUTStudents = 100PROCESS100 DIV 45 = 2100 MOD 45 = 10, so round up to 3EmptySeats = 3 × 45 − 100 = 35OUTPUTCoaches needed: 3 · Empty seats: 35

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.

IdentifierData typePurposeExample value
CoachSeatsINTEGERthe number of seats on one coach (a constant)45
StudentsINTEGERthe number of students going on the trip100
CoachesINTEGERthe number of coaches needed, rounded up3
EmptySeatsINTEGERthe number of seats left empty35
StudentNameSTRINGa student's full name, for the booking list"Ali Khan"
TicketPriceREALthe price of one ticket in dollars12.50
HasPaidBOOLEANTRUE once the student has paidTRUE
TripDateDATEthe scheduled departure date12/04/2026
Identifier · typeMeaning · example
CoachSeats
INTEGER
the number of seats on one coach (a constant)
Example: 45
Students
INTEGER
the number of students going on the trip
Example: 100
Coaches
INTEGER
the number of coaches needed, rounded up
Example: 3
EmptySeats
INTEGER
the number of seats left empty
Example: 35
StudentName
STRING
a student's full name, for the booking list
Example: "Ali Khan"
TicketPrice
REAL
the price of one ticket in dollars
Example: 12.50
HasPaid
BOOLEAN
TRUE once the student has paid
Example: TRUE
TripDate
DATE
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_Scoreletters, digits and _ only; starts with a letter; meaningful
Not valid  2ndMark, Total Cost, Cost$, NEXTstarts with a digit; has a space; has a symbol; is a keyword
Poor  X for a pricenot meaningful: harder to understand, debug and maintain
Your turn

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. 1
    Coaches = 130 DIV 45 = 2; 130 MOD 45 = 40, not 0, so add 1: 3. EmptySeats = 3 × 45 − 130 = 5
  2. 2
    90 MOD 45 = 0, so the IF condition is FALSE: 2 coaches, 0 empty seats
  3. 3
    2Total: a name has to begin with a letter, not a digit
Tick what you can do now
Exam focusIn an identifier table, the purpose says what the value means in this problem (“the number of coaches needed”), not its type (“stores an integer”). Names such as A, B and C do not show the purpose of the variable and make maintenance harder.
Practise with s25/21 Q1(a); s24/22 Q1(c); s24/21 Q1(c)(i), (c)(ii); s22/21 Q1(a) (older paper: algorithm term)
3 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Sequence, selection and iteration

§9.2 · Algorithms · the three basic constructs

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.

Set Temp to FirstSet First to SecondSet Second to Tempone step after another
Pseudocode
Temp ← First
First ← Second
Second ← Temp

Selection

A condition decides which steps run. Only one of the two paths is taken.

Is Mark >= 40 ?YESNOOUTPUT "Pass"OUTPUT "Fail"the two paths join again
Pseudocode
IF Mark >= 40 THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF

Iteration

Steps are repeated. Here the condition is tested before each pass.

Set Count to 1Is Count <= 5 ?YESOUTPUT Count * CountSet Count to Count + 1NO
Pseudocode
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 exampleWhy the construct is needed
Swap First and Secondsequence preserves First in Temp before overwriting it
Pass or failselection tests Mark against 40 and chooses one output
Squares 1 to 25iteration repeats the calculation for Count 1 through 5
Your turn

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. 1
    "Fail": 39 >= 40 is FALSE, so the ELSE path runs
  2. 2
    both hold 8: the 3 in First was overwritten before it was copied
  3. 3
    1, 4 and 9, each on its own line
  4. 4
    iteration: the input is repeated until a condition is met
Tick what you can do now
Exam focusName the construct and say how this algorithm uses it. To justify a loop, link it to the task: count-controlled because the number of iterations is known; conditional because the loop can stop as soon as the value is found.
Practise with w24/23 Q2(b); w25/23 Q2(b); s24/23 Q2(b); s24/23 Q5(a); w25/21 Q5(b)(ii); s26/23 Q1(a)
4 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Algorithm representations: structured English, pseudocode and flowcharts

§9.2 · Algorithms · structured English, pseudocode, flowchart

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.

STARTSet PassCount to 0Set Count to 1Is Count > 5 ?OUTPUT PassCountENDYESINPUT ScoreNOIs Score >= 50 ?Set PassCount toPassCount + 1YESNOSet Count to Count + 1Scores in input order72455038917245503891Count——111112222333334444555556666Score————72727272724545454550505050503838383891919191919191PassCount—0000011111111122222222233333
STARTSet PassCount to 0Set Count to 1Is Count > 5 ?INPUT ScoreNOIs Score >= 50 ?Set PassCount toPassCount + 1YESNOSet Count toCount + 1OUTPUT PassCountYESENDScores in input order72455038917245503891Count——111112222333334444555556666Score————72727272724545454550505050503838383891919191919191PassCount—0000011111111122222222233333

Structured English

1Set the pass count to zero.
2Repeat steps 3 and 4 five times.
3Input a score.
4If the score is 50 or more, add 1 to the pass count.
5Output the pass count.
Pseudocode
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.

A flowchart has no FOR symbol: the counter is set, tested and incremented in separate boxes.

Flowchart symbols

In a flowchart, the shape of a box tells you what kind of statement is inside it.

STARTTerminatorSTART or ENDProcessassignment, calculationInput / outputINPUT, OUTPUTDecisiona YES / NO questionSubroutinea procedure or functionFlow linethe next step
STARTTerminatorSTART / ENDProcessassignment / calculationInput / outputINPUT / OUTPUTDecisiontwo labelled exitsSubroutineprocedure / functionFlow linethe next step
Your turn

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.

  1. 1
    3: 50, 100 and 75 are at least 50; 49 and 0 are not
  2. 2
    the input / output parallelogram
  3. 3
    Answer
    IF Score >= 50 THEN
    PassCount ← PassCount + 1
    ENDIF
    
Tick what you can do now
Exam focusEach representation must keep the same logic: the same initialisation, the same test and the same point where output happens. In a flowchart, label both exits of every decision (YES / NO) and show the loop returning above the test it repeats.
Practise with s24/21 Q2(a)
5 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

A loop that stops after a target count

§9.2 · Algorithms · loop stopping rules

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.

Stop after three successes
 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

TriesScorePassCount
1721
245
3502
438
5913

What the two counters mean

  1. 1
    PassCount increases only when the score is 50 or more.
  2. 2
    Tries increases for every input, including 45 and 38.
  3. 3
    The loop tests PassCount, then outputs Tries: the two counters have different jobs.
The third success arrives on attempt 5, so Tries outputs 5. Reorder the same scores as 72, 91, 50, 45, 38: this loop stops after 3 inputs. The fixed-five algorithm always reads five inputs.

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.

One time round the loop: pass 3
Each line that runs is a row. Its value goes in that variable’s column: the blue row of the whole run below.
LineStatement that runsTriesScorePassCountOUTPUTWritesWhat happens
4INPUT Score50Score 50the third score
the third score
5Tries ← Tries + 13Tries 32 + 1: every input is an attempt
2 + 1: every input is an attempt
6IF Score >= 50 THENtest 50 >= 50 is true, so line 7 runs
test 50 >= 50 is true, so line 7 runs
7PassCount ← PassCount + 12PassCount 21 + 1
1 + 1
9UNTIL PassCount = 3test 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

TriesScorePassCountOUTPUTWhat decided it
start00lines 1 and 2 set both counters to 0
lines 1 and 2 set both counters to 0
pass 1172172 >= 50: PassCount 1; 1 = 3 is false: repeat
72 >= 50: PassCount 1; 1 = 3 is false: repeat
pass 224545 >= 50 is false: PassCount stays 1; 1 = 3 is false: repeat
45 >= 50 is false: PassCount stays 1; 1 = 3 is false: repeat
pass 3350250 >= 50: PassCount 2; 2 = 3 is false: repeat
50 >= 50: PassCount 2; 2 = 3 is false: repeat
pass 443838 >= 50 is false: PassCount stays 2; 2 = 3 is false: repeat
38 >= 50 is false: PassCount stays 2; 2 = 3 is false: repeat
pass 5591391 >= 50: PassCount 3; 3 = 3 is true: stop
91 >= 50: PassCount 3; 3 = 3 is true: stop
end5line 10 outputs Tries: five attempts for three successes
line 10 outputs Tries: five attempts for three successes
Reorder the same scores as 72, 91, 50, 45, 38: this loop stops after 3 inputs. The fixed-five algorithm always reads five.

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.

LoopCondition testedChoose it when…
Count-controlled
FOR … NEXT
the counter: runs from the start value to the end valuethe number of iterations is known, e.g. read exactly five scores
Conditional, pre-condition
WHILE … ENDWHILE
before the body; repeats while TRUEthe body may not need to run at all, or the loop can stop as soon as an item is found
Conditional, post-condition
REPEAT … UNTIL
after the body; stops when TRUEthe 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.
Your turn

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?

  1. 1
    4: the successes are 80, 50 and 51; the loop stops after the fourth input, so 90 is never read
  2. 2
    a count-controlled FOR loop: the number of iterations is known
  3. 3
    a score must be input at least once before PassCount can be tested, and the number of attempts is not known in advance
Tick what you can do now
Exam focusCount attempts separately from successful comparisons. A fixed input count and a target success count are different stopping conditions.
Practise with s26/21 Q4; s26/23 Q4; w25/21 Q5(b)(ii)
6 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Structured English and pseudocode

§9.2 · Algorithms · structured English

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

1Set Total and Days to zero.lines 2–3
2Input a rainfall reading.line 4
3Jump to step 7 if the reading is negative.line 5
4Add the reading to Total.line 6
5Add 1 to Days.line 7
6Repeat from step 2.lines 8–9
7Output Days and Total.line 10
Pseudocode12, 0, 7, 3, −1 → 4 days, total 22 mm
 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 XX ← 0 before the loop · X ← X + 1 or X ← X + Value
Repeat steps 3 to 5 ten timesFOR Count ← 1 TO 10 … NEXT Count
Jump to step 7 if the reading is negative … repeat from step 2WHILE 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

Ages until 0 is input; count those under 18 (12, 45, 17, 9, 0 → 3)
1Declare an integer Count and set it to zero.initialise
2Repeat steps 3 and 4 until the age input is 0.conditional loop
3Input the next age.input in the loop
4If the age is over 0 and under 18, add 1 to Count.test and update
5After the loop, output Count.output after

Rules

  • Number the steps, one action in each.
  • Name the loop and when it stops.
  • Plain English: no ←, ENDIF or DECLARE.
  • The value that ends the loop is not processed.
Your turn

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. 1
    3 days, total 14 mm: −2 ends the loop, so the 4 after it is never input
  2. 2
    FOR Count ← 1 TO 4 … NEXT Count, around the statements for steps 2 and 3
  3. 3
    Answer
    Count ← 0
    REPEAT
    INPUT Age
    IF Age > 0 AND Age < 18 THEN
    Count ← Count + 1
    ENDIF
    UNTIL Age = 0
    OUTPUT Count
    
Tick what you can do now
Exam focusTranslating: use the identifiers given and keep every step; a “jump” or “repeat from” step is a conditional loop. Writing structured English: plain-English steps, no pseudocode statements, but still initialise, loop, input, test and update, and output after the loop.
Practise with w24/23 Q2(a); s26/21 Q4; s26/23 Q4
7 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Writing pseudocode from a flowchart

§9.2 · Algorithms · flowchart to pseudocode

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).

STARTSet Tries to 0Set Connected to FALSEIs Connected = FALSEAND Tries < 3 ?YESSet Tries to Tries + 1Set Connected toTryConnect()Is Connected = TRUE ?NOOUTPUT "Ready"OUTPUT "Not connected"YESNOENDTryConnect responses: FALSE, TRUETries—000111222222Connected——FALSEFALSEFALSEFALSEFALSEFALSETRUETRUETRUETRUETRUEResponse—————FALSEFALSEFALSETRUETRUETRUETRUETRUE
STARTSet Tries to 0Set Connected to FALSEIs Connected = FALSEAND Tries < 3 ?Set Tries to Tries + 1Set Connected toTryConnect()YESIs Connected = TRUE ?NOOUTPUT "Ready"OUTPUT"Not connected"YESNOENDTryConnect responses: FALSE, TRUETries—000111222222Connected——FALSEFALSEFALSEFALSEFALSEFALSETRUETRUETRUETRUETRUEResponse—————FALSEFALSEFALSETRUETRUETRUETRUETRUE
Pseudocode: pre-condition loop
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
The same loop, post-condition
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() returnsTriesOutput
TRUE1"Ready"
FALSE, TRUE2"Ready"
FALSE, FALSE, FALSE3"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.

  1. 1
    Set Tries to 0, Set Connected to FALSE: process boxes become assignments, Tries ← 0 and Connected ← FALSE.
  2. 2
    Set Connected to TryConnect(): a subroutine box becomes a function call, Connected ← TryConnect() (or CALL for a procedure).
  3. 3
    Is Connected = FALSE AND Tries < 3 ?: its YES path goes back up above the test, so it becomes WHILE, keeping both conditions.
  4. 4
    Is Connected = TRUE ?: its two paths join again before END, so it becomes IF … ELSE … ENDIF.
  5. 5
    A test after the body that returns above the body becomes REPEAT … UNTIL. A counter that is set, tested and incremented can become FOR.
Your turn

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.

  1. 1
    3 tries, then "Ready": the third call returns TRUE just before the limit
  2. 2
    the subroutine box (a rectangle with double sides)
  3. 3
    UNTIL Connected = TRUE OR Tries >= 5: the NOT of Connected = FALSE AND Tries < 5
Tick what you can do now
Exam focusKeep both conditions of a combined decision. 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).
Practise with s24/22 Q2(b); w21/21 Q2(b) (older paper: bounded status loop)
8 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Drawing a flowchart

§9.2 · Algorithms · structured English or pseudocode to 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.

Structured English1Set PassCount and FailCount to zero.2Input a mark.3If the mark is −1, go to step 6.4If the mark is 40 or more, add 1 to PassCount, otherwise add 1 to FailCount.5Repeat from step 2.6Output PassCount and FailCount.STARTSet PassCount to 0Set FailCount to 0INPUT MarkIs Mark = -1 ?OUTPUT "Passed: ", PassCountOUTPUT "Failed: ", FailCountYESENDIs Mark >= 40 ?NOSet PassCount toPassCount + 1YESSet FailCount toFailCount + 1NO123456
Structured English1Set PassCount and FailCount to zero.2Input a mark.3If the mark is −1, go to step 6.4If the mark is 40 or more, add 1 toPassCount, otherwise add 1 to FailCount.5Repeat from step 2.6Output PassCount and FailCount.STARTSet PassCount to 0Set FailCount to 0INPUT MarkIs Mark = -1 ?Is Mark >= 40 ?NOSet PassCount toPassCount + 1Set FailCount toFailCount + 1YESNOOUTPUT "Passed: ", PassCountOUTPUT "Failed: ", FailCountYESEND123456

Checklist for a flowchart

Each point matches a numbered circle on the flowchart.

  1. 1
    One START and one END, in terminator shapes.
  2. 2
    Initialise counts and totals before the loop.
  3. 3
    Every decision is a question with two labelled exits: YES / NO or TRUE / FALSE.
  4. 4
    The loop line returns above the step to be repeated, here the INPUT.
  5. 5
    Inputs and outputs go in parallelograms; use the identifiers you are given.
  6. 6
    Output after the loop if it happens once.
The same algorithm in pseudocode
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.

Your turn

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. 1
    Passed: 1 and Failed: 1: 40 >= 40 is a pass; −1 stops the loop and is not counted
  2. 2
    no new mark is input: the same mark is tested again and again, so the loop never ends
  3. 3
    a decision diamond, with both exits labelled: YES and NO
Tick what you can do now
Exam focusMarks are given for functional groups: initialisation, the input in the loop, the test that ends the loop, each decision with its update, and the output. Label both exits so the selected path is unambiguous.
Practise with s24/21 Q2(a); s24/22 Q2(a); s22/22 Q2 (older paper: sentinel flowchart with function call)
9 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Stepwise refinement

§9.2 · Algorithms · 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.

OutlineRefinedRefined again2.1Input the student's mark2.2Work out the grade2.3Output the grade2.4Add the mark to the total3.1Divide the total by 253.2Output the average1Set the total to zero2Process each of 25 students3Output the class average2.2.1If mark ≥ 70: grade A2.2.2Else if mark ≥ 50: grade B2.2.3Else: grade Calready one assignment: no refinement neededFinal steps specify inputs,outputs, assignments and decisionconditions that translate directlyinto code.
1 Set the total to zeroAlready one assignment: no further refinement.2 Process each of 25 students2.1 Input the student's mark2.2 Work out the grade2.3 Output the grade2.4 Add the mark to the total2.2.1 If mark ≥ 70: grade A2.2.2 Else if mark ≥ 50: grade B2.2.3 Else: grade C3 Output the class average3.1 Divide total by 253.2 Output the averageRefinement expands a step into programmable detail.

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.

1Write an outline
A few big steps that solve the whole problem, in order.
passes onsteps 1, 2 and 3
2Refine each step
Break each step that hides detail into smaller steps: 2 becomes 2.1 to 2.4.
passes onmore detailed steps
3Repeat until code
Refine again until every step is one input, output, assignment or decision.
resultsteps ready to code

The finished steps become code one line at a time; the comment on each line names the step it came from.

Refined to code
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.

Your turn

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.

  1. 1
    50 → B, 70 → A, 49 → C: the tests are >= 70, then >= 50
  2. 2
    it is already one assignment (Total ← 0), so it can be coded directly
  3. 3
    no: it hides a decision with two conditions, so it is refined into 2.2.1 to 2.2.3
Tick what you can do now
Exam focusTwo points describe stepwise refinement: increase the level of detail (break steps into smaller steps) … until each step can be programmed. When asked for steps “without pseudocode”, write precise actions in words: set, input, check, add, repeat, output.
Practise with s25/22 Q2(a); s24/23 Q2(a); w23/21 Q2(a) (older paper: outlining selected totals in words)
10 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Logic statements

§9.2 · Algorithms · logic statements in an algorithm

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

OperatorMeaning
=equal to
<>not equal to
< · <=less than · less than or equal to
> · >=greater than · greater than or equal to

Logic operators

OperatorTRUE when…
ANDboth conditions are TRUE
ORat least one condition is TRUE
NOTthe 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.

Age >= 13 AND Age <= 1910111213141516171819202122TRUE only inside: both comparisons TRUETemp < 18 OR Temp > 24141516171819202122232425262728TRUE on either side: one comparison is enough
Age >= 13 AND Age <= 1910111213141516171819202122TRUE only inside: both comparisons TRUETemp < 18 OR Temp > 24141516171819202122232425262728TRUE on either side: one comparison is enough

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 wordsAs 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 rangeNOT ((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.

ExpressionEvaluates to
Age >= 13 AND Age <= 19TRUE
Paid AND NOT MemberTRUE
NOT (Paid OR Member)FALSE
Score MOD 10 = 2 OR Age < 12TRUE
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.

Your turn

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. 1
    (a) TRUE, (b) TRUE, (c) FALSE: in (c) NOT Member is FALSE, so AND gives FALSE
  2. 2
    (Size >= 1) AND (Size <= 10)
  3. 3
    FALSE: 24 < 18 is FALSE and 24 > 24 is FALSE, so neither side is TRUE (the open dot on the number line)
Tick what you can do now
Exam focusWrite a complete comparison on each side of AND and OR: 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.
Practise with s24/21 Q1(b); s26/22 Q1(a)(ii); s26/23 Q2(c)
11 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Selection with ranges and bands

§9.2 · Algorithms · logic statements for 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.

Is Value < 20 ?Is Value <= 50 ?Set Charge to 4.99Set Charge to 2.99Set Charge to 0.00NONOYESYESeach test is reached onlywhen the tests before itwere NO
Is Value < 20 ?Set Charge to 4.99YESIs Value <= 50 ?NOSet Charge to 2.99Set Charge to 0.00YESNOSecond test is reached only after the first is NO.
Nested IF: one band only
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

ValueBandCharge
19.99below 204.99
20.0020 to 502.99
50.0020 to 502.99
50.01above 500.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.

Separate IFs: both can run
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 Charge ends as 2.99, not 4.99.
  • Wrong order: if Value <= 50 is tested first, 10 also gets 2.99, and Value < 20 under its ELSE can never be TRUE.
  • Correct it: nest the IFs, and swap the two decisions.
Your turn

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.

  1. 1
    35 → 2.99, 75 → 0.00
  2. 2
    50.00 (the highest value charged 2.99) and 50.01 (the lowest value that is free)
  3. 3
    (Value >= 20) AND (Value <= 50)
Tick what you can do now
Exam focusCheck every band with its boundary values (here 19.99, 20, 50 and 50.01). If a flowchart puts its decisions in the wrong order, say which decision is wrong and how to reorder it.
Practise with s25/21 Q2(a)(i), (a)(ii), (b)(i), (b)(ii)
12 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Totalling, counting and averages

§9.2 · Algorithms · standard methods

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.

Total, count and mean
 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

CountMinutesTotalLongCountOUTPUT
00
12525
240651
330952
415110
5501603
623183
Total: 183
30 or more: 3
Mean: 30.5

Four places, four jobs

  1. 1
    Before the loop (lines 3–4): set Total and LongCount to 0.
  2. 2
    Inside the loop (lines 6–9): input, add to the total, test and count.
  3. 3
    After the loop (lines 12–14): output the results once.
  4. 4
    Mean = 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.

One time round the loop: pass 2
Each line that runs is a row. Its value goes in that variable’s column: the blue row of the whole run below.
LineStatement that runsCountMinutesTotalLongCountWritesWhat happens
5FOR Count ← 1 TO 62Count 2the next value of Count
the next value of Count
6INPUT Minutes40Minutes 40the second input
the second input
7Total ← Total + Minutes65Total 6525 + 40
25 + 40
8IF Minutes >= 30 THENtest 40 >= 30 is true, so line 9 runs
test 40 >= 30 is true, so line 9 runs
9LongCount ← LongCount + 11LongCount 10 + 1
0 + 1
11NEXT Counttest 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

CountMinutesTotalLongCountWhat decided it
start00lines 3 and 4 set Total and LongCount to 0
lines 3 and 4 set Total and LongCount to 0
pass 1125250 + 25 = 25; 25 >= 30 is false: LongCount is left blank
0 + 25 = 25; 25 >= 30 is false: LongCount is left blank
pass 224065125 + 40 = 65; 40 >= 30: LongCount 1
25 + 40 = 65; 40 >= 30: LongCount 1
pass 333095265 + 30 = 95; 30 >= 30: LongCount 2
65 + 30 = 95; 30 >= 30: LongCount 2
pass 441511095 + 15 = 110; 15 >= 30 is false: LongCount is left blank
95 + 15 = 110; 15 >= 30 is false: LongCount is left blank
pass 55501603110 + 50 = 160; 50 >= 30: LongCount 3
110 + 50 = 160; 50 >= 30: LongCount 3
pass 6623183160 + 23 = 183; 23 >= 30 is false: LongCount is left blank
160 + 23 = 183; 23 >= 30 is false: LongCount is left blank
endafter 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.

Mean of the selected values only
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 ← 0 inside the loop resets the total on every pass.
  • Dividing the selected total by all the inputs: 120 ÷ 6 = 20, not 40.
  • Using DIV for a mean loses the fraction: 183 DIV 6 = 30, not 30.5.
  • An OUTPUT inside the loop prints a running value after every input.
  • If the selected count can be 0, check it before dividing.
Your turn

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. 1
    Total: 180, 30 or more: 4, Mean: 30.0
  2. 2
    23: the total is reset on every pass, so only the last input is left
  3. 3
    37.5: 30 + 45 + 35 + 40 = 150, ÷ 4 values
Tick what you can do now
Exam focusThe mark points are: initialise total and count before the loop, input inside the loop, test and update inside the loop, calculate and output the mean after the loop. Divide by the number of values that were added to the total.
Practise with w24/23 Q2(a); s24/22 Q2(a)
13 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Maximum and minimum

§9.2 · Algorithms · standard methods

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.

Highest, lowest and its position
 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

DayTempHighestLowestColdDay
-2-2-21
2-9-92
311
4-4
5-9
6-3
70

Output: Highest: 1, Lowest: -9, Coldest day: 2.

Inputs −2, −9, 1, −4, −9, −3, 0

  1. 1
    Start from the first input (lines 3–6): Highest and Lowest are both −2.
  2. 2
    Loop through the other six (line 7): compare each with the best so far.
  3. 3
    Replace only when the new value is greater (or smaller). ColdDay records the day.
  4. 4
    Output 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.

One time round the loop: day 2
Each line that runs is a row. Its value goes in that variable’s column: the blue row of the whole run below.
LineStatement that runsDayTempHighestLowestColdDayWritesWhat happens
7FOR Day ← 2 TO 72Day 2the loop starts at the second day
the loop starts at the second day
8INPUT Temp-9Temp -9the second input
the second input
9IF Temp > Highest THENtest −9 > −2 is false: line 10 is skipped
test −9 > −2 is false: line 10 is skipped
12IF Temp < Lowest THENtest −9 < −2 is true
test −9 < −2 is true
13Lowest ← Temp-9Lowest -9the new lowest
the new lowest
14ColdDay ← Day2ColdDay 2remember where it was found
remember where it was found

The whole run: one row each day

DayTempHighestLowestColdDayWhat decided it
start-2-2-21lines 3–6: the first input starts Highest and Lowest; ColdDay 1
lines 3–6: the first input starts Highest and Lowest; ColdDay 1
day 22-9-92new lowest −9: ColdDay 2
new lowest −9: ColdDay 2
day 3311new highest 1
new highest 1
day 44-4neither test is TRUE: nothing changes
neither test is TRUE: nothing changes
day 55-9−9 = −9 is not lower: the first −9 is kept
−9 = −9 is not lower: the first −9 is kept
day 66-3neither test is TRUE: nothing changes
neither test is TRUE: nothing changes
day 770neither 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
Input the first temperature and assign it to Highest.
2
Loop through the remaining six temperatures, inputting each one in turn.
3
In the loop, if the temperature is greater than Highest, assign it to Highest.
4
After the loop, output Highest.
Your turn

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. 1
    Highest: 7, Lowest: −1, Coldest day: 3: the first −1 is on day 3
  2. 2
    day 6: with <= the later −1 replaces the first one
  3. 3
    if every input is below 0, a start of 0 would be output, a value that was never input
Tick what you can do now
Exam focusInitialise the maximum (or minimum) to the first value, then loop through the remaining values: six more for these seven inputs. Inside the loop, compare and replace only when the new value is greater (or smaller). Output after the loop.
Practise with s24/22 Q2(a); s21/21 Q2(c) (older paper: mean excluding maximum)
14 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Rogue values: ending a sequence of inputs

§9.2 · Algorithms · standard methods

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.

Pre-condition loop with a rogue value
 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

WeightTotalCountOUTPUT
2.50.00
4.02.51
1.56.52
4.08.03
0.012.04
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

  1. 1
    Read before the loop (line 5), so the first value can be tested.
  2. 2
    Test before processing (line 6): 0.0 stops the loop.
  3. 3
    Process, then read the next (lines 7–9).
  4. 4
    Check 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.

One time round the loop: pass 2
Each line that runs is a row. Its value goes in that variable’s column: the blue row of the whole run below.
LineStatement that runsWeightTotalCountOUTPUTWritesWhat happens
6WHILE Weight <> 0.0test 4.0 <> 0.0 is true, so the body runs
test 4.0 <> 0.0 is true, so the body runs
7Total ← Total + Weight6.5Total 6.52.5 + 4.0
2.5 + 4.0
8Count ← Count + 12Count 21 + 1
1 + 1
9INPUT Weight1.5Weight 1.5read the next weight at the end of the body
read the next weight at the end of the body
6WHILE Weight <> 0.0test 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

WeightTotalCountOUTPUTWhat decided it
start2.50.00lines 3–5: the first weight is read before the loop
lines 3–5: the first weight is read before the loop
pass 14.02.512.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 21.56.524.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 34.08.031.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 40.012.044.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
endMean: 3.00.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.

Post-condition: Total = 0, Count = 0
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.

DataValid valuesA suitable rogue value
parcel weights in kggreater than 00.0: no parcel weighs 0 kg
exam marks0 to 100-1: below the lowest possible mark
product codes (STRING)four digits"END": not a valid code
temperatures in °Cuse the task’s range; 0 and negative values can be valid999 only if reserved outside that range; otherwise input the count first
Your turn

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. 1
    Mean: 2.25: (3.5 + 1.0) ÷ 2 = 2.25
  2. 2
    No parcels: the WHILE test is FALSE at once, so Count stays 0 and the IF stops a division by 0
  3. 3
    for example −1: it is an integer like the ages, but no member can be −1 years old
Tick what you can do now
Exam focusUse a conditional loop that ends when the rogue value is input, and make sure the rogue value is not added or counted. Give the reason for a choice of rogue value: it is not a possible data value.
Practise with s26/21 Q4; s26/23 Q4; s22/22 Q5(a) (older paper: pre-condition loop termination); w23/22 Q4(b) (older paper: first-sentinel test data)
15 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Input validation loops

§9.2 · Algorithms · standard methods

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.

Post-condition: repeat until valid
REPEAT
OUTPUT "Enter a mark from 0 to 100"
INPUT Mark
UNTIL Mark >= 0 AND Mark <= 100
Pre-condition: with an error message
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

MarkMark < 0 OR Mark > 100OUTPUT
Enter a mark from 0 to 100
105TRUEInvalid: re-enter the mark
-3TRUEInvalid: re-enter the mark
67FALSE

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.

One time round the loop: pass 1
Each line that runs is a row. Its value goes in that variable’s column: the blue row of the whole run below.
LineStatement that runsMarkOUTPUTWritesWhat happens
3WHILE Mark < 0 OR Mark > 100test 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
4OUTPUT "Invalid: re-enter the mark"Invalid: re-enter the markOUTPUT Invalid: re-enter the marksay what was wrong
say what was wrong
5INPUT Mark-3Mark -3a new value replaces the invalid one
a new value replaces the invalid one
3WHILE Mark < 0 OR Mark > 100test back to the test with −3
test back to the test with −3

The whole run: one row each time round the loop

MarkOUTPUTWhat decided it
start105Enter a mark from 0 to 100lines 1–2: prompt, then the first input
lines 1–2: prompt, then the first input
pass 1-3Invalid: re-enter the mark105 > 100, so the condition is TRUE: error message, input again
105 > 100, so the condition is TRUE: error message, input again
pass 267Invalid: 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
end67: 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
The WHILE condition describes an invalid mark; the UNTIL condition describes a valid one. Each is the NOT of the other: 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.

CheckThe input is valid when…
LengthLENGTH(Code) = 6
Length rangeValid: (LENGTH(Code) >= 4) AND (LENGTH(Code) <= 6); invalid: (LENGTH(Code) < 4) OR (LENGTH(Code) > 6)
PresenceName <> ""
Whole numberValue = INT(Value)
Odd numberSize MOD 2 = 1
Validation with limited attempts
Tries ← 0
REPEAT
INPUT Guess
Tries ← Tries + 1
UNTIL Guess = 4071 OR Tries = 3
IF Guess = 4071 THEN
OUTPUT "Unlocked"
ELSE
OUTPUT "Locked"
ENDIF
Your turn

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?

  1. 1
    the prompt is output 2 times; 100 is accepted: 100 <= 100 is TRUE
  2. 2
    Answer
    REPEAT
    INPUT Size
    UNTIL Size MOD 2 = 1
    
  3. 3
    "Locked": three wrong guesses make Tries = 3, so the loop stops
Tick what you can do now
Exam focusPut the input inside the loop so a new value is read each time, and test the whole rule: a range check needs both limits. An error message should say what was wrong or what is expected.
Practise with s26/22 Q1(a)(ii)
16 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Tracing an algorithm

§9.2 · Algorithms · dry run and trace table

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.

Pseudocode
 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

NumberDigitTotalCountOUTPUT
372500
372551
3727
37142
0317
17 2

Rules for a trace table

  1. 1
    Follow the statements in the order they run, not the order they are written.
  2. 2
    Write a value only when a line changes it; a blank means no change.
  3. 3
    Record OUTPUT when the OUTPUT statement runs, exactly as output.
  4. 4
    Check 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.

One time round the loop: pass 1
Each line that runs is a row. Its value goes in that variable’s column: the blue row of the whole run below.
LineStatement that runsNumberDigitTotalCountOUTPUTWritesWhat happens
4WHILE Number > 0test 3725 > 0 is true, so the body runs
test 3725 > 0 is true, so the body runs
5Digit ← Number MOD 105Digit 53725 MOD 10: the last digit
3725 MOD 10: the last digit
6Total ← Total + Digit5Total 50 + 5
0 + 5
7IF Digit > 4 THENtest 5 > 4 is true, so line 8 runs
test 5 > 4 is true, so line 8 runs
8Count ← Count + 11Count 10 + 1
0 + 1
10Number ← Number DIV 10372Number 3723725 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

NumberDigitTotalCountOUTPUTWhat decided it
start372500lines 1–3: input 3725; Total and Count start at 0
lines 1–3: input 3725; Total and Count start at 0
pass 13725513725 MOD 10 = 5; 5 > 4: Count 1; 3725 DIV 10 = 372
3725 MOD 10 = 5; 5 > 4: Count 1; 3725 DIV 10 = 372
pass 23727372 MOD 10 = 2; 2 > 4 is false; 372 DIV 10 = 37
372 MOD 10 = 2; 2 > 4 is false; 372 DIV 10 = 37
pass 33714237 MOD 10 = 7; 7 > 4: Count 2; 37 DIV 10 = 3
37 MOD 10 = 7; 7 > 4: Count 2; 37 DIV 10 = 3
pass 403173 MOD 10 = 3; 3 > 4 is false; 3 DIV 10 = 0
3 MOD 10 = 3; 3 > 4 is false; 3 DIV 10 = 0
end17 20 > 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: choose inputs and expected results, then follow each statement using a trace table. Compare actual values and paths with the requirements. In the earlier separate-IF example, Value 10 sets Charge to 4.99 then overwrites it with 2.99: the trace locates the logic error.

Walkthrough testing

A dry run is also a test: it shows the point where an algorithm stops doing what was intended.

  1. 1
    Choose inputs and the expected results.
  2. 2
    Follow each statement in a trace table.
  3. 3
    Compare 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.)
Your turn

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. 1
    12 1: digits 8, 0, 4 give Total 12; only 8 is more than 4
  2. 2
    5 times, once for each digit (Number becomes 5002, 500, 50, 5, 0)
  3. 3
    0 (or any value not above 0): WHILE Number > 0 is FALSE at the first test
Tick what you can do now
Exam focusFollow the actual path and the stated trace-table instructions. Here Number reaches 0, so the next WHILE test ends the loop.
Practise with s25/23 Q4(b); s22/22 Q5(b) (older paper: CASE and character trace)
17 / 18
9618 · Unit 9 · Algorithm design and problem-solving
Revisionbyexamplicity

Tracing nested loops

§9.2 · Algorithms · inner and outer loop control

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.

Nested loops
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

OuterInnerTotalOUTPUT
0
111
212
24
315
27
310
10

Two loops, one total

  1. 1
    Line 1 sets Total to 0 once, before both loops.
  2. 2
    Line 3 starts Inner at 1 again for every value of Outer.
  3. 3
    Line 4 runs 1 + 2 + 3 = 6 times in all.
  4. 4
    Line 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.

Outer 2: the inner loop runs twice
Each line that runs is a row. Its value goes in that variable’s column: the two blue rows below.
LineStatement that runsOuterInnerTotalOUTPUTWritesWhat happens
2FOR Outer ← 1 TO 32Outer 2the next value of Outer
the next value of Outer
3FOR Inner ← 1 TO Outer1Inner 1Inner starts again at 1; it will run to 2
Inner starts again at 1; it will run to 2
4Total ← Total + Inner2Total 21 + 1
1 + 1
5NEXT Inner2Inner 22 <= 2: run the body again
2 <= 2: run the body again
4Total ← Total + Inner4Total 42 + 2
2 + 2
5NEXT Innertest Inner would be 3, and 3 > 2: the inner loop ends
test Inner would be 3, and 3 > 2: the inner loop ends
6NEXT Outertest back to line 2 for Outer 3
test back to line 2 for Outer 3

The whole run: one row for each addition

OuterInnerTotalOUTPUTWhat decided it
start0line 1: Total is set to 0 once, before both loops
line 1: Total is set to 0 once, before both loops
add 1111Outer 1 starts a fresh inner loop: Inner 1; 0 + 1 = 1
Outer 1 starts a fresh inner loop: Inner 1; 0 + 1 = 1
add 2212Outer 2 starts a fresh inner loop: Inner 1; 1 + 1 = 2
Outer 2 starts a fresh inner loop: Inner 1; 1 + 1 = 2
add 324Inner 2 <= 2: 2 + 2 = 4
Inner 2 <= 2: 2 + 2 = 4
add 4315Outer 3 starts a fresh inner loop: Inner 1; 4 + 1 = 5
Outer 3 starts a fresh inner loop: Inner 1; 4 + 1 = 5
add 527Inner 2 <= 3: 5 + 2 = 7
Inner 2 <= 3: 5 + 2 = 7
add 6310Inner 3 <= 3: 7 + 3 = 10
Inner 3 <= 3: 7 + 3 = 10
end10Outer 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.

STARTSet Total to 0Set Outer to 1Is Outer > 3 ?Set Inner to 1Is Inner > Outer ?Set Total to Total + InnerSet Inner to Inner + 1Set Outer to Outer + 1OUTPUT TotalENDNONOYESYES
STARTSet Total to 0Set Outer to 1Is Outer > 3 ?Set Inner to 1Is Inner > Outer ?Set Total to Total + InnerSet Inner to Inner + 1Set Outer to Outer + 1OUTPUT TotalENDNONOYESYES

Reset the inner counter, preserve the total

1
Set Total to 0 only once, before either loop.
2
For each Outer value, set Inner back to 1. Each completed inner loop advances Outer.
3
When the outer loop ends, output Total 10. These body snapshots stop at Outer 3 / Inner 3, before the loop-control increments.
Your turn

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?

  1. 1
    20: the old 10, plus 1 + 2 + 3 + 4 for Outer 4
  2. 2
    10 times: 1 + 2 + 3 + 4
  3. 3
    6: Total is reset for each Outer, so only the last pass (1 + 2 + 3) is left
Tick what you can do now
Practise with s25/21 Q4(b)
18 / 18