1.2.1 - Control flow, input and output

1.2.1 - Control flow, input and output

Algorithms are where a solution stops being a vague idea and becomes a route that someone else can follow. In this lesson, you will read and write sequence, selection, count-controlled repetition, condition-controlled repetition and iteration, while keeping input, processing and output clear. You will express the same logic as flowcharts, pseudocode and short program-code examples.

Algorithms and data flow

Algorithm

An algorithm is a finite, ordered set of unambiguous steps that solves a problem or completes a task.

An algorithm describes the method, not just the final answer. It must be precise enough for the same valid input to be handled in the intended way. Algorithms can be represented in three forms:

RepresentationWhat it isWhat must be clear
FlowchartA diagrammatic representation using standard shapes and directed arrowsThe order, decisions, branches and loops
PseudocodeAn informal written description of an algorithmThe logic and indentation; no single strict syntax is required
Program codeInstructions written using a programming language's syntaxThe exact statements and structure used by that language

Most useful algorithms can also be understood as input, processing and output:

StageMeaningTicket-kiosk example
InputData supplied to the algorithmThe customer enters 3 tickets
ProcessingWork carried out using the inputCalculate the cost at GBP 6 per ticket
OutputInformation produced by the algorithmDisplay 18

The input is not necessarily the first value visible in an algorithm, and the output is not simply the last variable used. Ask instead: What data enters the solution? What is done with it? What information leaves the solution?

Sequence and selection

Sequence

Sequence is the execution of instructions in their stated order, one after another.

Sequence still exists inside a branch or loop. It does not mean that the whole algorithm must be one straight path.

Selection

Selection uses a condition to choose which path through an algorithm is followed.

In a two-way selection, one branch is followed when the condition is true and the other when it is false. The algorithm then continues with the next instruction after the selection.

Consider this Python 3 program code as a written Paper 1 algorithm:

Python
tickets = int(input())          # 01
total = tickets * 6             # 02
if tickets >= 5:                # 03
    print("Group booking")      # 04
else:                           # 05
    print("Standard booking")   # 06
print(total)                    # 07

With the supplied input 6, line 1 accepts the input and line 2 processes it to produce 36. The condition on line 3 is true, so line 4 is followed and lines 5-6 are skipped. Line 7 then follows in sequence.

Predicted screen output for input 6:

Plain text
Group booking
36

The common near-miss is to treat if and else as two instructions that both run. They are alternative paths: only the matching branch is followed.

Two kinds of repetition

Repetition

Repetition executes the same block of steps more than once.

The correct loop depends on what controls the repetition.

Count-controlled repetition

Count-controlled repetition runs a block a known or determined number of times.

This written Python algorithm produces three copies of Scan:

Python
for count in range(1, 4):   # 01
    print("Scan")           # 02

The values supplied by range(1, 4) are 1, 2 and 3; the stop value 4 is not included. The chosen range therefore controls three passes.

Condition-controlled repetition

Condition-controlled repetition runs a block while a condition remains true.

Python
doors_open = 2                       # 01
while doors_open > 0:                # 02
    print("Check door")              # 03
    doors_open = doors_open - 1      # 04
print("Complete")                    # 05

For the supplied starting value 2, the condition is true twice. The predicted output is therefore:

Plain text
Check door
Check door
Complete

A while condition is checked before each pass. If doors_open began at 0, the loop body would execute zero times and only Complete would be output. This is different from assuming that every loop must run at least once.

When writing the two forms in pseudocode, make the controller visible:

Plain text
REPEAT <known number> TIMES
    <steps>
END REPEAT

WHILE <condition is true>
    <steps that can lead to a new condition result>
END WHILE

Iteration over items

Iteration

In this specification, iteration means repeating a block over every item in a data structure.

The loop is controlled by the actual items to be visited, not by a separately chosen number. Here the supplied data structure is a list of three parcel codes:

Python
parcel_codes = ["A2", "B1", "C4"]   # 01
for code in parcel_codes:             # 02
    print(code)                        # 03

The first pass uses A2, the second uses B1 and the third uses C4. The predicted output is:

Plain text
A2
B1
C4

Compare the controlling ideas:

FormWhat controls the next pass?Typical written form
Count-controlled repetitionA known or determined number of passesfor number in range(...)
Condition-controlled repetitionWhether a condition is still truewhile condition:
IterationWhether another item remains in the data structurefor item in structure:

Count-controlled repetition and iteration can happen to make the same number of passes, but that does not make them identical. for position in range(3) is controlled by three generated numbers; for code in parcel_codes is controlled by the three actual parcel-code items.

Flowchart control

Flowchart

A flowchart is a diagrammatic representation of an algorithm using symbols connected by directed flow lines.

A flowchart makes the route through an algorithm visible. It is useful for seeing the order of processing, where a decision splits the route, and where a loop returns to an earlier condition without depending on one programming language's syntax.

Pearson uses six symbols in Paper 1 questions:

Symbol appearanceMeaning
Rounded start/end shapeStart or end of the algorithm
RectangleA process or action
ParallelogramInput or output
DiamondA decision or condition
Directed arrowThe logical flow and direction
Rectangle with double vertical sidesA pre-defined subprogram

[DIAGRAM: asset_name: Flowchart symbols and a condition-controlled loop; asset_slug: 1_2_1_control_flow_input_and_output__diagram_01; recommended_method: image_gen; description: Original 16:9 monochrome teaching diagram. The left panel shows the six Pearson Paper 1 flowchart symbols with exact short labels Start/End, Process, Input/Output, Decision, Flow line and Pre-defined subprogram. The right panel shows Start leading to INPUT jobs, then decision jobs > 0?; Yes leads to PROCESS Complete one job, then PROCESS jobs = jobs - 1, with an arrow returning to the decision; No leads to OUTPUT Done and then End. Both decision outcomes are labelled, all arrows are directed, and there are no hanging paths.]
Diagram

In the worked loop, the decision is tested before the process. The Yes route completes one job, changes the amount remaining and returns to the same decision. The No route leaves the loop, outputs Done and reaches the end. A decision diamond contains the question; an action such as Complete one job belongs in a process rectangle.

When writing a flowchart, check that every symbol is connected, every arrow has an unambiguous direction, and every two-way decision has two clearly labelled outcomes that reach the correct next step.

Complete algorithms

Real algorithms combine constructs. The key is to decide what controls each section rather than choosing a construct because its keyword looks familiar.

Requirement: A reviewer inputs a minimum rating. The supplied data structure is ratings = [4, 2, 5]. For every rating, output Recommend when it meets the minimum and Review otherwise. After every item has been handled, output Finished.

One clear pseudocode solution is:

Plain text
INPUT minimum_rating
FOR EACH rating IN ratings
    IF rating >= minimum_rating THEN
        OUTPUT "Recommend"
    ELSE
        OUTPUT "Review"
    END IF
END FOR
OUTPUT "Finished"

With supplied input 4, the algorithm visits ratings 4, 2 and 5 in turn. The selection produces Recommend, Review and Recommend. Only after the iteration has finished does the final instruction run in sequence.

Predicted output:

Plain text
Recommend
Review
Recommend
Finished

This one algorithm contains all of the following relationships:

  • Input: the minimum rating.
  • Processing: compare each supplied rating with the minimum and choose a message.
  • Iteration: visit every item in ratings.
  • Selection: choose one of two messages for the current item.
  • Sequence: output Finished only after the loop ends.
  • Output: the three item messages followed by the final message.

Control flow answers one question: which instruction happens next? Sequence fixes the order, selection chooses a path, and repetition or iteration sends control through a block again.

To write a new algorithm, first state the required input and output. Put unavoidable steps into sequence, use selection only where a condition chooses a path, then choose a fixed count, a continuing condition or every-item iteration for any repeated block. Finally, follow each possible route on paper to check that it reaches the intended output.