A-Level Computer Science / Unit 9: Computational Thinking and Algorithm Design

9.2.3 Sequence, Decisions, Loops and Logic

πŸ”’ Lesson slides are available to signed-in users. Sign in

9.2.3 Sequence, Decisions, Loops and Logic

Algorithms control what happens next. Some instructions always run in order, some run only when a condition is true, and others repeat. This section develops the three core control structures and shows how comparison and logical operators create precise conditions.

By the end of this section, you should be able to:

  • Use sequence to place dependent steps in a correct order.
  • Use assignment statements to store and update values within an algorithm.
  • Write a selection structure that chooses between alternative paths.
  • Construct conditions using relational operators and the logical operators AND, OR and NOT.
  • Use iteration to repeat a block of pseudocode.
  • Combine sequence, selection and iteration in one coherent solution.
  • Trace variable values and condition outcomes to check an algorithm.
This page develops algorithm design. Detailed programming syntax, nested decisions, CASE structures and choosing between loop implementations are revisited in Unit 11.

The Three Core Control Structures

A control structure determines the order in which instructions are followed. Most algorithms can be designed by combining sequence, selection and iteration.

Construct Main question Effect on control flow Typical use
Sequence What must happen first, next and last? Runs instructions once in their written order. Input values, calculate a result, then output it.
Selection Which path should be followed? Chooses a path according to a Boolean condition. Apply a discount only when eligibility rules are met.
Iteration Which instructions must happen again? Repeats a block a known number of times or while a condition applies. Process every sensor reading in a batch.
Exam tip: Do not name a construct without explaining its effect. For example, state that selection tests a condition and follows one of the available paths.

Sequence and Assignment

In a sequence, each instruction is completed before the next one begins. The order matters whenever a later instruction depends on a value produced earlier.

INPUT JourneyMinutes
TravelCharge ← JourneyMinutes * 0.45
FinalCharge ← TravelCharge + 2.50
OUTPUT FinalCharge

The calculation of FinalCharge must come after TravelCharge has been calculated. Reversing those lines would use a value that is not ready.

Assignment: storing a value in an identifier. An update such as ReadyCount ← ReadyCount + 1 reads the old value, calculates a new one and stores it back.
PseudocodeWhat happens
ReadyCount ← 0Initialises a counter before it is used.
ReadyCount ← ReadyCount + 1Increases the current value by one.
SafeToHire ← BrakeOK AND BatteryLevel >= 25Stores the Boolean result of a logic statement.
Common mistake: The assignment symbol ← means β€œstore the result on the right in the identifier on the left”. It is not the same as testing equality with =.

Selection: Making a Decision

Selection tests a condition whose result is TRUE or FALSE. The result determines which block of instructions is followed.

IF BatteryLevel >= 25 THEN
    OUTPUT "Battery ready"
ELSE
    OUTPUT "Recharge required"
ENDIF

The two output statements are alternatives: only one is executed for a particular value of BatteryLevel.

OperatorMeaningExample condition
=Equal toStatus = "OPEN"
<>Not equal toChoice <> "Q"
<Less thanStockLevel < 8
<=Less than or equal toSoundLevel <= 55
>Greater thanTemperature > 30
>=Greater than or equal toBatteryLevel >= 25
Exam tip: Check whether a boundary value is included. β€œAt least 25” requires >= 25, not > 25.

Logic Statements: Combining Conditions

A simple condition contains one comparison. A compound condition joins or changes Boolean expressions using AND, OR or NOT.

Logical operatorWhen the whole condition is trueOriginal example
AND Both parts are true. BrakeOK = TRUE AND TyrePressure >= 32
OR At least one part is true. Temperature > 45 OR BatteryLevel < 15
NOT The following Boolean value is reversed. NOT DoorLocked

Choosing between AND and OR

// A reading is inside the accepted range only when both limits are satisfied
Humidity >= 35 AND Humidity <= 70

// An alert is needed when either unsafe situation occurs
Temperature > 45 OR BatteryLevel < 15
Common mistake: A value cannot be below 35 and above 70 at the same time. To test whether a value lies outside that range, use Humidity < 35 OR Humidity > 70.
Exam tip: Use parentheses when a condition contains several operators. They make the intended grouping easier to read and reduce ambiguity.

Iteration: Repeating a Block

Iteration, also called repetition or looping, avoids writing the same instructions many times. A loop needs a clear rule that controls how often the block is repeated.

TotalEnergy ← 0
FOR ReadingNumber ← 1 TO 4
    INPUT EnergyReading
    TotalEnergy ← TotalEnergy + EnergyReading
NEXT ReadingNumber
OUTPUT TotalEnergy

The assignment inside the loop creates a running total. Initialising TotalEnergy before the loop is essential because every new reading is added to its current value.

Loop ideaUseful whenImportant property
Count-controlledThe number of repetitions is known.A counter records progress through the repetitions.
Pre-conditionThe block should run only while a condition is already true.The block may execute zero times.
Post-conditionThe block must run before its stopping condition is tested.The block executes at least once.
The exact pseudocode forms FOR, WHILE and REPEAT...UNTIL, including how to justify a choice between them, are developed further in Unit 11.
Common mistake: A condition-controlled loop must make progress towards its stopping rule. If the controlling value never changes, the algorithm may repeat indefinitely.

Worked Example: Checking Returned E-Bikes

A hire centre checks four returned e-bikes. A bike is ready for hire only when the brakes pass, the tyre pressure is at least 32 psi and the battery level is at least 25%. The algorithm must report the result for each bike and count how many are ready.

How the constructs are combined

ConstructRole in the solution
SequenceInitialise the counter, read the three checks, evaluate the condition and produce an output.
IterationRepeat the inspection for four returned bikes.
Logic statementCombine the three safety requirements using AND.
SelectionEither count the bike as ready or send it for further inspection.

Pseudocode

ReadyCount ← 0

FOR BikeNumber ← 1 TO 4
    INPUT BrakeOK
    INPUT TyrePressure
    INPUT BatteryLevel

    SafeToHire ← BrakeOK = TRUE
                  AND TyrePressure >= 32
                  AND BatteryLevel >= 25

    IF SafeToHire = TRUE THEN
        ReadyCount ← ReadyCount + 1
        OUTPUT "Ready for hire"
    ELSE
        OUTPUT "Further inspection required"
    ENDIF
NEXT BikeNumber

OUTPUT ReadyCount
Exam tip: Indentation does not change the logic by itself, but it makes the scope of the loop and decision much easier to verify.

Tracing the Combined Algorithm

A trace records how identifiers and conditions change. The table below uses three sample inspections from a shortened version of the algorithm.

Bike BrakeOK TyrePressure BatteryLevel SafeToHire ReadyCount after decision
1TRUE3562TRUE1
2TRUE2971FALSE1
3FALSE3448FALSE1

Bike 2 fails because one part of an AND condition is false. Bike 3 also fails, even though its tyre pressure and battery level are acceptable, because the brake test is false.

Interactive: Control-Flow Trace

Choose a construct and move through the pseudocode one step at a time. Watch the current line, variable values and condition result. The existing assignment-trace widget structure has been retained and expanded to cover the whole lesson.

Current pseudocode line
INPUT JourneyMinutes

The sample input is stored before any calculation uses it.

JourneyMinutes empty
TravelCharge empty
FinalCharge empty

Step 1 of 4

Read the input

Select Next step to store the sample journey time.

Common Mistakes and Misconceptions

  • Writing instructions in an order that uses a value before it has been input or calculated.
  • Using = for assignment or ← when testing equality.
  • Using > when a boundary should be included with >=.
  • Using AND when either condition should trigger an action.
  • Forgetting to initialise a counter or running total before a loop.
  • Repeating a block without changing the value used by the stopping condition.
  • Placing an instruction outside a loop or decision when it should be inside the block.
  • Adding complex nested structures when a simpler condition would communicate the same logic.

Practice

Try these original questions

  1. Put these steps in a valid sequence for calculating the area of a solar panel: output area, input width, calculate width Γ— height, input height.
  2. Write a condition that is true when Score is from 40 to 75 inclusive.
  3. Write a condition that triggers an alert when Temperature exceeds 42 or Pressure falls below 18.
  4. Write pseudocode to input Age and output "Eligible" when the value is at least 16; otherwise output "Not eligible".
  5. Write a count-controlled loop that inputs five rainfall readings and calculates their total.
  6. The condition Humidity < 30 AND Humidity > 80 is intended to detect an unsafe humidity value. Explain the error and correct it.
  7. Trace this pseudocode and state the final value of Total:
    Total ← 2
    FOR Counter ← 1 TO 3
        Total ← Total + Counter
    NEXT Counter
  8. Design pseudocode that repeats three times, inputs a package mass, and outputs "Heavy" when the mass is above 12.5 kg or "Standard" otherwise.
  9. Explain how sequence, selection and iteration are all used in the e-bike worked example.

Review

QuestionStrong answer should include
What is sequence?Instructions executed once in a defined order, with dependencies respected.
What is selection?A Boolean condition chooses which path or block is followed.
What is iteration?A block of instructions repeats according to a count or condition.
What is a relational operator?An operator such as <, >= or <> that compares values.
When is AND true?Only when every joined condition is true.
When is OR true?When at least one joined condition is true.
What does NOT do?Reverses a Boolean value or condition result.
How can an algorithm be checked?Trace statements in order, recording values and the result of each condition.
Final exam tip: Test compound conditions with values at, just below and just above each boundary. This exposes many logic errors before the algorithm is implemented.