Year 7 · Scratch I & II · Part C: Telling it what to do

Algorithms

In one line

An algorithm is a precise, step-by-step plan to solve a problem. Computational thinking turns a messy problem into one. Every algorithm is built from just three things: sequence, selection and iteration.

1

Say what makes a set of instructions an algorithm: precise, ordered, finite.

2

Use decomposition, pattern recognition, abstraction and algorithmic thinking on a real problem.

3

Read and write the same algorithm as a flowchart, AQA and OCR pseudocode, and Scratch blocks.

4

Dry-run an algorithm with a trace table, count loop repeats, and spot the bug.

5

Compare two algorithms by counting their steps.

AlgorithmPrecise, ordered, finite steps to solve a problem.
DecompositionBreaking a problem into smaller ones.
AbstractionIgnoring detail that doesn't matter.
Sequence · selection · iterationIn order · choose a path · repeat.
PseudocodeCode-like writing without strict rules.
Trace tableRecords every variable, step by step.
VariableA named box that holds one value.

What an algorithm is

A recipe is an algorithm. So are directions to a friend's house. An algorithm is a list of steps that solves a problem. For a computer, it must be three things.

It must be…MeaningBreaks the rule
PreciseNo step can be misunderstood"Add some salt." How much?
OrderedSteps happen in a set orderShoes, then socks
FiniteIt must stop"Keep stirring." Until when?
!Watch out

Computers are totally literal. "Put jam on the bread" could mean putting the jar on the bread. A computer never guesses what you meant. It does exactly what you wrote.

The algorithmthe plan, the idea:"add up 1 to 5" The computerruns machinecode (Topic 10) Left side: written for people. Only a real program can be run, after a translator turns it into machine code.
One plan, written many ways. The algorithm is the idea. A program is that idea written in a programming language (Scratch, Python).
▶

Be the robot's programmer

The robot (the arrow) only understands: forward, forward 3, left, right, repeat 4 … end. It turns on the spot. Get it to the gold star without hitting a grey wall.

?Why?

Why did "go to the star" not work? It isn't precise. The robot doesn't know where the star is or how to get round walls. You had to decide every move and its order, and your list ended. Precise, ordered, finite: you just wrote an algorithm.

Computational thinking: four tools for any problem

Before you can write an algorithm, you have to understand the problem. Computational thinking is four habits that turn a big, messy problem into clear steps.

The four tools, used on "Plan the Year 7 trip". They don't have to happen strictly in this order; you go back and forth.
ToolWhat you doEveryday example
DecompositionBreak a big problem into smaller ones you can solve one at a time"Make a game" → player, movement, enemies, score
Pattern recognitionSpot what's similar. Solve it once, reuse itMoving up, down, left, right is the same script four times
AbstractionIgnore detail that doesn't matter for this problemThe Tube map ignores real distances
Algorithmic thinkingWrite the exact steps, decisions and repeatsThe robot instructions in Step 1
▶

Decompose a problem

Tap a part to break it down. Keep going until every piece is small enough to do in one go (green).

    Abstraction: the London Tube map

    Left: where things really are. Right: Harry Beck's 1933 map keeps only what a passenger needs: which stations, in what order, and where to change. Real distances and bends are thrown away.
    ?Why?

    Why throw information away? Less detail = a smaller problem = fewer mistakes. A Scratch football game doesn't need the weather or the players' names. What you keep depends on the question: a cyclist needs a map with real distances; a Tube passenger doesn't.

    Input, process, output, and the three building blocks

    Before writing any algorithm, ask three questions. What goes in? What must happen? What comes out? Then build the "happen" part from only three kinds of block.

    ProblemInputProcessOutput
    Average of three test marksThree marksAdd them, divide by 3The average
    Is a number even?A numberFind the remainder when ÷ 2"even" or "odd"
    Scratch cat chases the mouse pointerMouse positionPoint towards it, move 5 steps, repeatCat moves on the stage
    Sequence goes straight down. Selection splits into two paths, then joins. Iteration has an arrow going back up.
    BlockMeaningEverydayScratch
    SequenceSteps in order, one after anotherSocks, then shoesBlocks snapped in a stack
    SelectionChoose a path (if… else…)If it rains, umbrella; else sunglassesif <> then … else
    IterationRepeat (loops)Stir 20 times; or stir until smoothrepeat 10, repeat until, forever
    ★Remember

    Every program ever written, from Scratch to a phone's operating system, is built from just these three. Even the robot in Step 1: its lines are a sequence, and repeat is iteration.

    Flowcharts: an algorithm as a picture

    A flowchart draws an algorithm. Each shape means one kind of step. Arrows show what comes next. Learn the six symbols: exam boards use the same ones.

    Colours here are just to help you tell them apart. In an exam, only the shape counts.
    ShapeMeansExample text inside
    Rounded oval (terminator)Start / StopStart
    ParallelogramInput or outputINPUT age · OUTPUT total
    RectangleA process (do something)total ← total + 5
    DiamondA yes/no decisionage ≥ 13 ?
    Rectangle with double sidesA subroutine (a named mini-algorithm)drawSquare
    ArrowWhat comes next
    1. A decision always has two arrows out, labelled Yes and No.

    2. A loop is an arrow going back up to an earlier step.

    3. Exactly one Start. Every path must reach a Stop, or the algorithm isn't finite.

    e.g.Example

    "Can I see this film?" Start → INPUT age → diamond age ≥ 12? → Yes: OUTPUT "Enjoy the film" / No: OUTPUT "Sorry, too young" → Stop. That's input, selection, output.

    One algorithm, four ways: flowchart, pseudocode, Scratch

    Here is one algorithm: count from 1 to 6 and say whether each number is odd or even. Below it is written four ways. Same plan, different spelling.

    The trick for odd/even is the remainder. Divide by 2. Remainder 0 → even. Remainder 1 → odd. In pseudocode, the remainder is called MOD.

    1. 7 ÷ 2 = 3 remainder 1. So 7 MOD 2 = 1 → odd.

    2. 8 ÷ 2 = 4 remainder 0. So 8 MOD 2 = 0 → even.

    3. Check 7: 3 × 2 + 1 = 7 ✓. Check 8: 4 × 2 + 0 = 8 ✓.

    4. So the selection is: IF n MOD 2 = 0 THEN even ELSE odd. The remainder decides the path.

    Flowchart. Two diamonds: the first is the loop (iteration), the second is the if (selection). A FOR loop in a flowchart becomes a counter, a test and "add 1".

    AQA 8525 pseudocode

    FOR n ← 1 TO 6
        IF n MOD 2 = 0 THEN
            OUTPUT n, " is even"
        ELSE
            OUTPUT n, " is odd"
        ENDIF
    ENDFOR

    OCR J277 Exam Reference Language

    for n = 1 to 6
        if n MOD 2 == 0 then
            print(str(n) + " is even")
        else
            print(str(n) + " is odd")
        endif
    next n

    Scratch (Year 7)

    when ⚑ clicked
    set n ▾ to 1
    repeat 6
    if n mod 2 = 0 then
    say join n is even for 1 seconds
    else
    say join n is odd for 1 seconds
    change n ▾ by 1
    1 is odd 2 is even 3 is odd 4 is even 5 is odd 6 is even
    IdeaAQA pseudocodeOCR reference languageScratch
    Store a valuen ← 1n = 1set n to 1
    Equals test===( ) = ( )
    Count loopFOR … TO … ENDFORfor … to … nextrepeat 10
    Condition loopWHILE … ENDWHILE
    REPEAT … UNTIL
    while … endwhile
    do … until
    repeat until < >
    OutputOUTPUTprint()say
    InputUSERINPUTinput()ask and wait → answer
    RemainderMODMOD( ) mod ( )
    ?Why?

    Why use pseudocode at all? It looks like code but ignores strict rules, so you think about the logic, not commas and brackets. In the exam, any sensible pseudocode gets the marks; the official styles just help you read the questions.

    e.g.The Scratch loop is different

    Scratch's repeat 6 has no counter, so we made one ourselves: set n to 1 before, change n by 1 inside. That is exactly what the FOR loop does for you behind the scenes.

    Run a flowchart, one shape at a time

    This algorithm adds up 1 + 2 + … + n. Press Next and follow the glowing shape. Watch the variable boxes and the trace table fill in.

    ▶

    Run the flowchart

    INPUT n =
    countcount ≤ n?totaloutput
    ?Why?

    Try n = 0. The very first test, 1 ≤ 0, is already No. The loop body never runs, and the output is 0. A WHILE loop checks before it runs, so it can run zero times.

    Count-controlled vs condition-controlled loops

    There are two kinds of iteration. A count-controlled loop knows how many times before it starts. A condition-controlled loop keeps going until something becomes true.

    Left: the computer counts for you, so it stops after exactly 10. Right: nobody knows how many stirs it will take; it stops when the condition says so.
    Count-controlledCondition-controlled
    Stops whenIt has run a set number of timesA condition becomes true (or stops being true)
    Know how many before it starts?YesNo
    AQAFOR i ← 1 TO 10WHILE x < 100 · REPEAT … UNTIL
    OCRfor i = 1 to 10 … next iwhile … endwhile · do … until
    Scratchrepeat 10repeat until <touching edge?>
    Python (Year 8)for i in range(1, 11):while x < 100:

    How many times does it repeat?

    FOR loops in pseudocode include both ends. So FOR i ← 3 TO 7 runs for 3, 4, 5, 6, 7.

    1. Rule: repeats = last − first + 1. The "+ 1" is because both ends count.

    2. FOR i ← 3 TO 7: 7 − 3 + 1 = 5. Check by listing: 3, 4, 5, 6, 7. Five. ✓

    3. FOR i ← 0 TO 9: 9 − 0 + 1 = 10.

    4. With a STEP: FOR i ← 0 TO 20 STEP 5 → 0, 5, 10, 15, 20. (20 − 0) ÷ 5 + 1 = 5.

    5. Loop inside a loop: repeat 4 with repeat 3 inside. The inside block runs 4 × 3 = 12 times.

    6. Python is different: range(3, 7) stops before 7: 3, 4, 5, 6. That's 7 − 3 = 4 times. (Year 8.)

    !Watch out: infinite loops

    If the condition can never be met, the loop never stops: x ← 1 · WHILE x > 0 · x ← x + 1. x only grows. The algorithm is no longer finite. In Scratch, forever is infinite on purpose (games run until you press stop), which is fine for a program but not for an algorithm that must give an answer.

    e.g.WHILE vs REPEAT UNTIL

    WHILE checks first, so it might run 0 times. REPEAT … UNTIL checks at the end, so it always runs at least once. "REPEAT ask for the password UNTIL it is correct": you must ask at least once.

    Variables in algorithms

    A variable is a named box that holds one value. Putting a new value in throws the old one away. In pseudocode the arrow ← means "put this value into this box".

    Before score10 score ← score + 5 ① read the right side: 10 + 5 ② work it out: 15 ③ put 15 in the box on the left After score1510 "score ← score + 5" is not maths. It's an instruction: work out the right, store it on the left.
    1. Name it well. total, lives, guess. Not x, unless it really is just a number.

    2. Give it a starting value before you use it: total ← 0. In Scratch: set total to 0 under the green flag. Forget it, and the old value from last time is still there.

    3. A counter goes up by 1: count ← count + 1. A running total adds things up: total ← total + mark.

    ▶

    Swap two variables

    Goal: make a = 7 and b = 3. Press the instructions in the order you think works.

    ?Why?

    Why does a ← b then b ← a fail? After the first line, both boxes hold 7. The 3 has been thrown away, so there is nothing left to copy back. You need a third box, temp, to hold one value safe. The order of a sequence matters.

    Trace tables: dry-run an algorithm

    A trace table has one column for each variable. You go through the algorithm by hand, line by line, and write a new value every time one changes. This is called a dry run: running it on paper, not on a computer.

    1numbers ← [7, 3, 12, 5]
    2biggest ← numbers[0]
    3FOR EACH n IN numbers
    4    IF n > biggest THEN
    5        biggest ← n
    6    ENDIF
    7ENDFOR
    8OUTPUT biggest

    numbers[0] means "item number 0", the first item. Lists count from 0.

    Your turn, by hand

    1x ← 1
    2steps ← 0
    3WHILE x < 20
    4    x ← x × 3
    5    steps ← steps + 1
    6ENDWHILE
    7OUTPUT steps, x
    Linexstepsx < 20?Output
    ★Remember

    Only write in a column when that variable changes. Leave it blank otherwise; that's how examiners expect it. Read down a column to see a variable's whole life.

    Finding errors, and counting steps

    A dry run catches mistakes before the computer does. The most common one is being off by one: the loop runs once too many or once too few.

    Meant to: output the 5 times table up to 5 × 5.

    1i ← 1
    2WHILE i < 5
    3    OUTPUT i × 5
    4    i ← i + 1
    5ENDWHILE
    ii < 5?Output
    1Yes5
    2Yes10
    3Yes15
    4Yes20
    5No(stops: 25 is missing!)
    !The bug

    When i = 5, the test 5 < 5 is false, so 25 never prints. Fix: WHILE i ≤ 5. The trace table showed it in seconds.

    Kind of errorWhat happensExample
    Logic errorIt runs, but the answer is wrong< instead of ≤ above
    Wrong order (sequence)Steps right, order wrongOutput total before adding the last number
    Not initialisedA variable is used before it gets a starting valueForgot total ← 0
    Infinite loopNever stopsForgot i ← i + 1
    Syntax error (in real code)Breaks the language's grammar; won't runPython: missing colon after if x > 3

    Efficiency: how many steps?

    Two algorithms can give the same answer, but one can take far fewer steps. To add up 1 + 2 + … + 100, you could loop 100 times. Or use the trick a young Carl Gauss is said to have spotted at school.

    1. Write the sum forwards and backwards: 1 + 2 + … + 100 and 100 + 99 + … + 1.

    2. Add them in pairs: 1 + 100 = 101, 2 + 99 = 101, … Every pair makes 101.

    3. There are 100 pairs, so the two lists together make 100 × 101 = 10,100.

    4. That's two copies of the sum, so halve it: 10,100 ÷ 2 = 5,050.

    5. General rule: total = n × (n + 1) ÷ 2. That's 3 steps (×, +, ÷) whatever n is, instead of n additions.

    ▶

    Count the steps

    ?Why?

    Why care, when computers are fast? A billion steps a second sounds like plenty. But "compare everyone with everyone" grows with n × n. For 1 million users, that's about 500 billion comparisons: over 8 minutes, every single time. Topic 12 (searching and sorting) is all about this.

    Common mix-ups

    The mistakes nearly everyone makes the first time. Read the left side, then the right.

    People think

    An algorithm and a program are the same thing.

    Actually

    The algorithm is the plan. A program is that plan written in a programming language.

    People think

    Abstraction means breaking a problem into parts.

    Actually

    That's decomposition. Abstraction is removing detail that doesn't matter.

    People think

    "if" is a loop.

    Actually

    "if" is selection: it runs once and picks a path. Only loops repeat.

    People think

    FOR i ← 1 TO 10 runs 9 times (10 − 1).

    Actually

    Both ends count: 10 − 1 + 1 = 10 times.

    People think

    x ← x + 1 is a false equation.

    Actually

    It's an instruction: work out x + 1, then store it back in x.

    People think

    A flowchart rectangle is used for input.

    Actually

    Input and output are parallelograms. Rectangles are processes. Decisions are diamonds.

    People think

    If it gives the right answer once, the algorithm is correct.

    Actually

    Test the edges too: n = 0, n = 1, the last item. Off-by-one bugs hide there.

    Check yourself

    Quick questions first. Then endless practice: a wrong answer shows you the working, step by step.

    [ {"q":"Breaking a problem into smaller parts is…","o":["Abstraction","Decomposition","Iteration"],"a":1,"w":"De-compose = take apart."}, {"q":"An 'if… else…' is…","o":["Sequence","Selection","Iteration"],"a":1,"w":"It selects one path."}, {"q":"In a flowchart, a decision is a…","o":["Diamond","Rectangle","Oval"],"a":0,"w":"Diamonds have yes/no arrows coming out."}, {"q":"The Tube map leaves out real distances. That's…","o":["Abstraction","Decomposition","Pattern recognition"],"a":0,"w":"Abstraction removes detail that doesn't matter for the problem."}, {"q":"How many times does FOR i ← 2 TO 8 repeat?","o":["6","7","8"],"a":1,"w":"Both ends count: 8 − 2 + 1 = **7** (2, 3, 4, 5, 6, 7, 8)."}, {"q":"Which loop always runs at least once?","o":["WHILE … ENDWHILE","REPEAT … UNTIL","FOR i ← 1 TO 0"],"a":1,"w":"REPEAT … UNTIL checks its condition at the **end**, after the first run."}, {"q":"x ← 4, then x ← x × 2, then x ← x + 1. What is x?","o":["9","8","12"],"a":0,"w":"4 × 2 = 8, then 8 + 1 = **9**. Each line replaces the old value."}, {"q":"Which shape is used for OUTPUT total?","o":["Rectangle","Parallelogram","Diamond"],"a":1,"w":"Input and output are always parallelograms."} ]