7 Algorithm design and problem-solving

Test yourself on Algorithm design and problem-solving 13 questions — drag-to-order, code completion, matching and multiple choice.
Start the quiz

Computational Thinking

Watch this lesson Video 7.1 · 7:23 · Abstraction, decomposition, and the development cycle they sit inside

1. What is an Algorithm?

An Algorithm is a set of step-by-step instructions used to solve a specific problem or complete a task.

Input ➔ Process ➔ Output

An algorithm must be finite (it must end), unambiguous (clear instructions), and effective (it must actually solve the problem).

2. Key Concepts in Computational Thinking

Abstraction

The process of filtering out unnecessary details and focusing only on the information needed to solve the problem.

Example: A map of a subway doesn't show buildings or trees, only the stations and lines.

Decomposition

Breaking down a complex problem into smaller, more manageable sub-problems that are easier to solve individually.

Example: Breaking the task of "Making a Cake" into "Buying ingredients," "Mixing," and "Baking."

3. The Program Development Life Cycle (PDLC)

Developing software is a structured process. Each stage depends on the completion of the previous one.

Stages of the PDLC
1. Analysis
Understanding the problem. Outcome: Requirements Specification (Input, Process, Output requirements).
2. Design
Planning how the software will look and work. Outcome: Flowcharts, Pseudocode, and Structure Diagrams.
3. Coding
Writing the actual program using a high-level language. Outcome: Source Code.
4. Testing
Running the program to find and fix errors. Outcome: Test Report and Bug-free software.
5. Maintenance
Updating the program over time. Outcome: Updated software and patches.

4. Testing: Ensuring Accuracy

During the testing stage, we use different types of data to see if the program breaks. Here is the Testing Toolkit at a glance:

  • Normal Data: Expected data that should be accepted (e.g., age 25).
  • Abnormal/Erroneous Data: Data of the wrong type or outside limits that should be rejected (e.g., "twenty" or -5).
  • Extreme Data: The largest and smallest values at the very edges of the valid range (e.g., 1 and 100).
  • Boundary Data: Pairs of values at the limit: one just valid (e.g., 100) and one just invalid (e.g., 101).
⚠️ Exam Tip: When asked for the difference between Extreme and Boundary data: Extreme data is valid; Boundary data includes one valid and one invalid value.

Flowchart Symbols

Watch this lesson Video 7.2 · 7:37 · Six shapes, and the rules that decide which one you need

1. Standard Flowchart Symbols

Using the correct shapes is essential for exam marks. Each shape represents a specific type of instruction.

Shape Name Function
START / STOP
Terminator Used at the very beginning and the end of every flowchart.
X ← A + B
Process Used for calculations or assigning values to variables.
INPUT / OUTPUT
Input / Output Used when the program gets data from a user or displays a result.
Decision Used for Selection (IF statements). Has two exit paths: Yes and No.
PRE-DEFINED
Pre-defined Process Used for Subroutines or Functions defined elsewhere.

2. Example Algorithm: Pass/Fail Checker

Let's represent an algorithm that asks for a student's mark and tells them if they passed (Pass mark = 50).

START
INPUT Mark
Mark ≥ 50?
YES
OUTPUT "Pass"
NO
OUTPUT "Fail"
STOP

3. Drawing Rules

  • Flowcharts should generally flow from top to bottom or left to right.
  • Arrowheads must be used on all lines to show the direction of flow.
  • Decision symbols must have exactly two output lines, clearly labeled (e.g., True/False or Yes/No).
⚠️ Exam Warning: Do not confuse the Process (Rectangle) with the Input/Output (Parallelogram). Marks are frequently lost for using a rectangle when asking for a user's name!

Structure Diagrams

Watch this lesson Video 7.3 · 6:41 · Decomposing a system into sub-systems — and describing each by what goes in and out

1. Top-Down Design

Top-Down Design is the process of breaking a main problem into smaller parts (sub-problems) until each part is simple enough to be solved. A Structure Diagram is the visual tool used to show this hierarchy.

2. Example: Smart Alarm Clock System

Notice how the main system is decomposed into three main modules, which are then broken down further.

Smart Alarm Clock
Set Alarm
Input Time
Check Time
Compare to Current
Trigger Alarm
Sound Buzzer

2b. Describing a Sub-system: Input, Process, Output

Decomposing a system produces sub-systems, and the exam does not usually stop at naming them. It asks you to describe each one in terms of its inputs, its processes and its outputs — because that is what turns a box on a diagram into something a programmer could actually build.

Sub-system Inputs Processes Outputs
Set Alarm Hours and minutes entered by the user Validate the time is in range; store it in memory Confirmation shown on the display
Check Time Current time from the clock; stored alarm time Compare the two values A signal when they match
Trigger Alarm The match signal; the volume setting Start the sound; begin the snooze timer Buzzer sounds; display flashes
Why this is the useful form. Notice that one sub-system's output becomes the next one's input — Check Time produces a signal, and Trigger Alarm consumes it. Writing the IPO for each sub-system is how you find out whether your decomposition actually joins up. If a sub-system needs an input that nothing produces, the decomposition is incomplete, and you have discovered that on paper rather than halfway through writing the program.

3. Key Rules for Structure Diagrams

  • Hierarchy: The "Parent" module is at the top; "Children" modules are below.
  • No Logic: Unlike flowcharts, structure diagrams do not show decisions (IF) or loops (WHILE). They only show the components of the system.
  • Modularization: Each box represents a discrete task that could be written as a separate subroutine (function/procedure).

4. Advantages of Modular Design

Easier Debugging: It is easier to find and fix an error in a small module of 10 lines than in a program of 1,000 lines.
Collaboration: Different programmers can work on different modules at the same time.
Reusability: Once a module is written (e.g., a "Calculate Tax" module), it can be used in other programs.
Maintenance: Modules can be updated or replaced individually without breaking the entire system.
⚠️ Exam Tip: If an exam asks you to "Complete a structure diagram," remember to check the levels. Ensure the new module you add is a sub-task of the module directly above it.

Trace Tables

Watch this lesson Video 7.4 · 6:41 · Following an algorithm line by line — the skill that finds logic errors

1. What is a Trace Table?

A Trace Table is a tool used to track the values of variables as an algorithm executes line by line. Its primary purpose is to find Logic Errors that a compiler might miss.

2. Example: Totaling & Counting

Let's trace this pseudocode algorithm which finds the total and count of 3 numbers entered by a user.

Total ← 0
Count ← 0
WHILE Count < 3 DO
  INPUT Num
  Total ← Total + Num
  Count ← Count + 1
ENDWHILE
OUTPUT Total

Trace Table (Test Data: 10, 5, 20)

Total Count Num OUTPUT
0 0
10
10 1
5
15 2
20
35 3
35

3. Rules for Drawing Trace Tables

  • Each row represents a change in a variable's value or an input.
  • Do not repeat values in a row if they haven't changed (leave the cell blank or use a dash).
  • Output only goes in the output column when the program explicitly executes an OUTPUT or PRINT command.
  • Calculations (like Total + Num) are performed first, then the new value is written in the table.

4. Why use Trace Tables?

  • To verify that an algorithm works correctly with Test Data.
  • To identify Infinite Loops (where a variable never meets the exit condition).
  • To find "Off-by-one" errors (e.g., using Count < 3 vs Count <= 3).
⚠️ Exam Warning: When filling out a trace table in an exam, be very careful with Loops. The most common mistake is forgetting to increment the counter or stopping one iteration too early.

Standard Methods of Solution

Watch this lesson Video 7.5 · 9:03 · Six patterns that appear in almost every algorithm question

1. What Is a Standard Method of Solution?

Certain small tasks appear again and again inside larger programs: adding up a list, counting how many items match a condition, finding the biggest value, searching for an item, or putting data in order. These recurring solutions are called standard methods of solution. Learning them means you never have to invent them under exam pressure.

The syllabus limits this to six methods: linear search, bubble sort, totalling, counting, and finding maximum, minimum and average values. You are expected to recognise them, explain them, and write them.

2. Totalling

Totalling means adding every value in a set of data to produce a running sum.

The essential detail is that the total must be set to 0 before the loop starts. Initialising it inside the loop resets it on every pass and the answer is always the last value.

DECLARE Total : INTEGER DECLARE Number : INTEGER Total ← 0 // MUST be outside the loop FOR Count ← 1 TO 10 OUTPUT "Enter a number: " INPUT Number Total ← Total + Number NEXT Count OUTPUT "The total is ", Total

3. Counting

Counting means keeping track of how many items there are, or how many meet a condition. Note the difference from totalling: totalling adds the values, counting adds 1.

DECLARE PassCount : INTEGER PassCount ← 0 FOR Count ← 1 TO 30 INPUT Mark IF Mark >= 50 THEN PassCount ← PassCount + 1 // add 1, not the mark ENDIF NEXT Count OUTPUT PassCount, " students passed"
Totalling versus counting is a classic trap. If a question asks how many students scored over 50, the answer is a count (+ 1). If it asks for the combined score of those students, that is a total (+ Mark). Read which one is wanted.

4. Finding Maximum and Minimum

To find the largest value, hold a "best so far" variable and replace it whenever a bigger value appears.

DECLARE Highest : INTEGER DECLARE Lowest : INTEGER INPUT Number Highest ← Number // start both at the FIRST value Lowest ← Number FOR Count ← 2 TO 10 INPUT Number IF Number > Highest THEN Highest ← Number ENDIF IF Number < Lowest THEN Lowest ← Number ENDIF NEXT Count OUTPUT "Highest: ", Highest OUTPUT "Lowest: ", Lowest
Do not initialise Highest to 0. If every value is negative, the answer stays 0, which is wrong. Setting it to 0 also fails a boundary check. Start from the first data item instead, then loop from the second.

5. Finding an Average

An average combines totalling and counting: total the values, count them, then divide.

Total ← 0 Count ← 0 REPEAT INPUT Number IF Number <> -1 THEN Total ← Total + Number Count ← Count + 1 ENDIF UNTIL Number = -1 // -1 is the rogue value IF Count > 0 THEN // guard against dividing by zero OUTPUT "Average: ", Total / Count ELSE OUTPUT "No data entered" ENDIF
A rogue value (or sentinel) is a value outside the valid range used to signal the end of input. It must not be included in the total or the count.

6. Linear Search

A linear search checks each item in turn, from the start, until the target is found or the data runs out.

DECLARE Names : ARRAY[1:20] OF STRING DECLARE Found : BOOLEAN DECLARE Index : INTEGER Found ← FALSE Index ← 1 WHILE Index <= 20 AND Found = FALSE IF Names[Index] = SearchName THEN Found ← TRUE ELSE Index ← Index + 1 ENDIF ENDWHILE IF Found = TRUE THEN OUTPUT "Found at position ", Index ELSE OUTPUT "Not found" ENDIF
AdvantagesDisadvantages
The data does not need to be sorted firstSlow on large data sets
Simple to write and understandMay have to check every item to find nothing
Use a flag and stop early. A search that keeps looping after the item is found still "works" but wastes effort, and answers that never stop searching are penalised. The Found = FALSE condition in the WHILE is what stops it.

7. Bubble Sort

A bubble sort repeatedly compares neighbouring pairs and swaps them if they are in the wrong order. After each pass the largest remaining value has "bubbled" to the end.

DECLARE Numbers : ARRAY[1:6] OF INTEGER DECLARE Temp : INTEGER FOR Pass ← 1 TO 5 FOR Index ← 1 TO 5 IF Numbers[Index] > Numbers[Index + 1] THEN Temp ← Numbers[Index] // 3-step swap Numbers[Index] ← Numbers[Index + 1] Numbers[Index + 1] ← Temp ENDIF NEXT Index NEXT Pass

Worked trace of one pass

Starting data: 5, 3, 8, 1

CompareSwap?List after
5 and 3Yes, 5 > 33, 5, 8, 1
5 and 8No3, 5, 8, 1
8 and 1Yes, 8 > 13, 5, 1, 8

The largest value, 8, is now at the end. That is guaranteed after every pass, which is why the sort works.

The swap needs three steps and a temporary variable. Writing A ← B then B ← A destroys the first value — both end up the same. Marks are routinely lost here. Always: save to Temp, copy across, restore from Temp.

8. Exam Focus

Initialise before the loop, not inside it. Totals and counters set to 0 inside the loop are the most frequent single error in this topic.
Be precise in written answers. "It compares the numbers" is not enough for a bubble sort. Say that it compares adjacent or neighbouring items and swaps them if they are in the wrong order, repeating until no swaps are needed.

Quick self-check

  • State the difference between totalling and counting.
  • Explain why Highest should not start at 0.
  • Write the three lines needed to swap two array elements.
  • Give one advantage and one disadvantage of a linear search.
  • After one full pass of a bubble sort, which value is certainly in its final position?

Validation and Verification Checks

Watch this lesson Video 7.6 · 7:31 · Two different jobs — is the data sensible, and is it what was meant?

1. Why Check Input Data At All?

Programs cannot assume that the data entered is sensible. Users mistype, misread instructions, or deliberately enter nonsense. If bad data reaches the processing stage, the output is wrong — and the program may crash.

Two different jobs, often confused:
Validation asks “is this data reasonable?” — done automatically by the program.
Verification asks “has this data been copied or typed accurately?” — checks for mistakes during entry.

The distinction matters because a value can pass one and fail the other. A date of birth of 14/07/2009 is perfectly valid — but if the student was actually born in 2010, it is not verified. Validation cannot detect that; only verification can.

2. Validation Checks

The syllabus requires six validation checks. Learn what each one rejects, and one example of each.

CheckWhat it testsExample
Range check The value falls between a stated lower and upper limit A month must be from 1 to 12; 13 is rejected
Length check The data has an exact number, or an acceptable number, of characters A password must be at least 8 characters
Type check The data is of the required data type Age must be an integer; "twelve" is rejected
Presence check Data has actually been entered and the field is not empty An email address cannot be left blank
Format check The data follows a required pattern of characters A date entered as dd/mm/yyyy
Check digit An extra digit calculated from the others, recalculated to confirm the number was entered correctly The final digit of a barcode or ISBN

A range check in pseudocode

REPEAT OUTPUT "Enter a month (1 to 12): " INPUT Month IF Month < 1 OR Month > 12 THEN OUTPUT "Invalid - must be between 1 and 12" ENDIF UNTIL Month >= 1 AND Month <= 12
A validation check must do two things: reject the invalid data and ask again. A check that prints an error message but then carries on with the bad value has not validated anything.

Length check versus format check

These are easy to mix up. A length check counts characters. A format check inspects the arrangement of characters.

Data enteredLength check (must be 7)Format check (2 letters then 5 digits)
AB12345PassesPasses
1234567PassesFails — no letters
AB123Fails — only 5Fails

How a check digit works

A check digit is calculated from the other digits and stored as part of the number. When the number is entered, the program repeats the calculation and compares the result with the digit supplied. If they differ, a digit was mistyped or transposed.

  • It detects a single mistyped digit
  • It detects two digits swapped round (transposition), e.g. 45 typed as 54
  • It detects missing or extra digits

3. Verification Checks

The syllabus requires two verification methods.

MethodHow it worksTypical use
Visual check The person entering the data reads it back on screen and compares it with the original source document Checking a typed address against a paper form
Double entry check The data is entered twice and the computer compares the two versions. If they differ, at least one is wrong Confirming a new password or email address
A visual check is not the computer checking the data. It is a human comparing what is on screen with the original. Describing it as the program "looking at" the data does not earn the mark.
Why double entry is not foolproof: if the user makes the same mistake twice, the two entries match and the error passes. This is a valid evaluation point in extended-answer questions.

4. Validation and Verification Together

Real systems use both, because they catch different problems.

ValidationVerification
Question askedIs the data reasonable?Was the data entered accurately?
Performed byThe program, automaticallyThe user, or the program comparing two entries
CatchesImpossible or badly formed valuesTyping and copying mistakes
MissesWrong but plausible valuesValues that are accurately copied but nonsensical

5. Exam Focus

Name the check, do not just describe it. Questions ask you to identify a suitable validation check. "Make sure the number isn't too big" scores nothing; "range check" scores the mark.
Give the limits when asked for a range check. State the actual boundaries relevant to the scenario, e.g. "a range check to ensure the mark is between 0 and 100", not simply "a range check".
Do not offer a type check where a range check is needed. A common error is answering "type check" for a value that is the right type but out of range. Check what the invalid data in the question actually is before choosing.
Validation is not verification. If a question asks for a verification method, only visual check and double entry check are acceptable. Listing range or length checks earns nothing.

Quick self-check

  • State the difference between validation and verification in one sentence each.
  • Name the six validation checks.
  • Give a value that passes a length check but fails a format check.
  • Explain one situation a double entry check fails to detect.
  • A field must contain a percentage. Name two suitable validation checks and state what each rejects.

Test Data and Test Plans

Watch this lesson Video 7.7 · 7:55 · Four kinds of test data, and how to choose values that actually prove something

1. What Is a Test Plan?

A test plan is a document that sets out what will be tested, the data that will be used, and the result that is expected before the test is run. Testing is not guessing: the expected outcome must be decided in advance, otherwise there is nothing to compare the actual outcome against.

A test plan records four things for every test: the type of test data, the data used, the expected outcome, and the reason for including that test.

2. The Four Types of Test Data

The syllabus limits test data to four types. Getting the definitions exactly right matters, because extreme and boundary data are frequently confused.

TypeDefinitionShould it be accepted?
Normal Data a user would typically enter, comfortably inside the valid range Yes
Abnormal Data the program should refuse — outside the range, or the wrong data type No — must be rejected
Extreme The largest and smallest acceptable values Yes
Boundary The largest/smallest acceptable value and the corresponding smallest/largest rejected value — a pair either side of the limit One accepted, one rejected
Extreme and boundary are not the same thing. Extreme data is a single value: the largest or smallest value that is still accepted. Boundary data is a pair of values that straddle the limit — the last one accepted and the first one rejected. Giving only the rejected value is not boundary data, and giving only one value where a pair is asked for loses the mark.
Worked distinction. A field accepts marks from 0 to 100.
Extreme data: 0 and 100 — both accepted.
Boundary data: 100 and 101 — 100 accepted, 101 rejected. Also 0 and -1 at the lower limit.

3. Worked Example: The Library Age Limit

Problem: A digital library allows users aged 5 to 18 to register. Any other age must be rejected.
Test typeInput dataExpected outcomeReason
Normal12AcceptedWell inside the valid range
Abnormal“Ten”Error messageWrong data type — string, not integer
Abnormal25RejectedCorrect type but outside the range
Extreme5AcceptedSmallest acceptable value
Extreme18AcceptedLargest acceptable value
Boundary18 and 1918 accepted, 19 rejectedTests the upper limit is set at exactly the right place
Boundary5 and 45 accepted, 4 rejectedTests the lower limit

4. Worked Example: The Discount Code

Problem: A shop application accepts a percentage discount between 1% and 50%.
Test typeInput dataExpected outcomeReason
Normal25Discount appliedTypical valid input
Abnormal-10RejectedNegative values are invalid here
Abnormal“half”RejectedWrong data type
Extreme1Discount appliedSmallest acceptable percentage
Extreme50Discount appliedLargest acceptable percentage
Boundary50 and 5150 accepted, 51 rejectedCatches a condition written as <= 51 by mistake
Why boundary testing finds real bugs. A condition written as IF Discount < 51 instead of IF Discount <= 50 behaves identically for normal data such as 25. Only the pair 50 and 51 exposes it. This is precisely why boundary data is worth including.

4b. Iterative Testing and Final Testing

Testing happens at two different scales, and the syllabus names both.

  • Iterative testing takes place during development. Each module or sub-system is tested as it is written, and the program is corrected and re-tested repeatedly — hence iterative. The point is to find a fault while the code that caused it is small and freshly written.
  • Final testing takes place after development, once all the modules are combined. The complete program is tested against the original requirements specification from the analysis stage, to confirm it does everything it was supposed to do.
Why both are needed. Iterative testing checks that each part works. Final testing checks that the parts work together, and that the finished program meets the requirements — two things no amount of module testing can establish. A program can be made entirely of modules that each pass their own tests and still fail as a whole, because modules pass data between them and nobody tested the joins.

This is also why final testing refers back to the requirements specification rather than to the code. Iterative testing asks does this module do what I intended? Final testing asks does this program do what the customer asked for? They are different questions, and only the second one can tell you the project succeeded.

5. Choosing Test Data Well

  • Cover every type — a plan with only normal data proves almost nothing
  • Include both ends of a range, not just the top
  • Include a wrong data type as well as an out-of-range value
  • State the expected outcome before running the test, not after
  • Give a reason for each test, so the plan shows why the data was chosen

6. Exam Focus

Give actual values, not descriptions. "A number that is too big" earns nothing. For a range of 5 to 18, write 25. Test data questions want data.
Abnormal data is not only out-of-range data. A value of the wrong data type — letters where a number is expected — is also abnormal, and is often the mark being looked for when the question asks for two different abnormal values.
Do not reuse the same value for two test types. If you offer 18 as extreme data, it cannot also be your only boundary answer — boundary needs the pair 18 and 19. Examiners credit each type separately.

Quick self-check

  • Define extreme data and boundary data, and state how they differ.
  • A password field accepts 8 to 12 characters. Give normal, abnormal, extreme and boundary test data.
  • Explain why testing only normal data is insufficient.
  • Give two abnormal values for a field that stores a month number, each invalid for a different reason.

Identifying and Correcting Errors

Watch this lesson Video 7.8 · 8:20 · The five faults that appear most often — and a method for finding any of them

1. Key Terms

TermMeaning
BugAn error in a program that stops it working as intended
DebuggingThe process of finding and removing errors from a program
Dry runWorking through an algorithm by hand, on paper, without running it on a computer
Trace tableA table used to record the value of every variable, output and prompt at each step of a dry run

2. Types of Error

Syntax errors

A syntax error breaks the rules of the language: a misspelled keyword, a missing bracket, a missing quotation mark. The program will not translate, so it cannot run at all.

Logic errors

A logic error means the program runs perfectly but produces the wrong result. The syntax is legal, so nothing warns you. These are the errors trace tables are designed to catch.

Syntax errorLogic error
Does the program run?NoYes
How it is spottedThe translator reports itThe output is wrong — found by testing or a dry run
ExampleOUPUT TotalUsing + where * was intended
“It does not work” is never an answer. When asked to identify an error, state which line is wrong, what is wrong with it, and what it should be. All three parts are usually needed for full marks.

3. The Five Errors That Appear Most Often

Exam questions give you a short algorithm containing deliberate mistakes. Almost all of them are one of the following.

(a) Initialising inside the loop

// WRONG - Total resets every pass FOR Count ← 1 TO 10 Total ← 0 INPUT Number Total ← Total + Number NEXT Count
// CORRECT - initialise once, before the loop Total ← 0 FOR Count ← 1 TO 10 INPUT Number Total ← Total + Number NEXT Count

Symptom: the total equals the last value entered.

(b) Off-by-one loop bounds

// WRONG - only 9 iterations, and misses item 10 FOR Count ← 1 TO 9

Symptom: one item is always missed, or the program tries to read past the end of an array. Check the count carefully: 1 TO 10 runs ten times, 0 TO 10 runs eleven.

(c) The wrong comparison operator

// WRONG - excludes the boundary value 50 IF Mark > 50 THEN OUTPUT "Pass"
// CORRECT - if 50 is a pass IF Mark >= 50 THEN OUTPUT "Pass"

Symptom: everything works except at the exact boundary. Confusing > with >= is the single most common logic error in this topic.

(d) An infinite loop

// WRONG - Index never changes, so the loop never ends Index ← 1 WHILE Index <= 10 OUTPUT Names[Index] ENDWHILE

Cause: the variable in the loop condition is never updated inside the loop. Every condition-controlled loop must contain something that eventually makes the condition false.

(e) A swap without a temporary variable

// WRONG - the first value is destroyed; both end up the same A ← B B ← A
// CORRECT - three steps via Temp Temp ← A A ← B B ← Temp

4. How to Find an Error Systematically

Do not read an algorithm hoping the mistake will stand out. Work through it:

  1. Read the stated purpose. You cannot judge whether an algorithm is wrong without knowing what it is meant to do.
  2. Check every initialisation. Are totals and counters set before the loop, not inside it?
  3. Check every loop bound. Count the iterations by hand.
  4. Check every comparison. Should it be > or >=?
  5. Dry run with a trace table using a small amount of data — three or four values is enough to expose most errors.
  6. Test the boundary specifically, because that is where operator errors hide.

Worked example

This algorithm should output the highest of five numbers. Find the errors.

Highest ← 0 FOR Count ← 1 TO 4 INPUT Number IF Number < Highest THEN Highest ← Number ENDIF NEXT Count OUTPUT Highest
LineErrorCorrection
Highest ← 0Fails if all five numbers are negativeInput the first number and set Highest to it
FOR Count ← 1 TO 4Only four numbers are read, not fiveFOR Count ← 1 TO 5
IF Number < HighestWrong operator — this finds the lowestIF Number > Highest
Notice that the algorithm would run without complaint and print a number. Nothing is syntactically wrong. All three faults are logic errors, and only a dry run reveals them.

5. Exam Focus

Suggest a correction, do not just identify the fault. The command word is usually “identify the errors and suggest ways of correcting them”. Half the marks are in the correction. Write the corrected line out in full.
Quote the line, or refer to its number. Answers that say "the loop is wrong" without saying which line, or what about it is wrong, cannot be credited.
Be precise, and use symbols. The syllabus requires precision in algorithms: x > y is acceptable, "x is greater than y" is not.

Quick self-check

  • State the difference between a syntax error and a logic error, and how each is detected.
  • Why does a total initialised inside a loop give the last value entered?
  • Write the three lines that correctly swap two values.
  • Give one reason a WHILE loop might never end.
  • An algorithm should accept marks of 40 and above. It uses IF Mark > 40. Which test data exposes the error?