Unit 4: Algorithms · Building algorithms

Article

Sequencing, selection and iteration

8 min read

You give a friend directions. "Walk to the corner. If the shop is open, buy some water. Then keep walking until you see a red door." There are three kinds of instruction here: plain steps, a choice, and a repeat. Every algorithm, from a calculator to a search engine, is built from just these three. This article names them, so you can find them in any code.

Sequencing: one step after another

Sequencing means the steps run one after the other, in the order written. The order matters:

AP pseudocode
x ← 3
x ← x * 2
x ← x + 1
DISPLAY(x)
After this linex is
x ← 33
x ← x * 26
x ← x + 17

It displays 7. Swap the two middle lines and x goes 3, 4, 8, so it displays 8. The same steps in a different order give a different answer.

Runs in your browser

Swap the two middle lines and run it again. A program with no IF and no loop is still an algorithm: it uses sequencing only. Every algorithm uses sequencing, because even the lines inside an IF or a loop run in order.

Selection: choosing a path

Selection decides which steps run, using a condition that is true or false. In AP pseudocode it is IF, with an optional ELSE.

AP pseudocode
temp ← 31
IF(temp > 30)
{
    DISPLAY("Hot")
}
ELSE
{
    DISPLAY("Fine")
}
Runs in your browser

It displays Hot. With selection, some steps are skipped: for one input, only one of the two blocks runs. An IF with no ELSE can skip everything. Change temp to 20 and run it again.

Iteration: repeating steps

Iteration repeats a group of steps. One run through the group is a pass. AP pseudocode has three loops: REPEAT n TIMES, REPEAT UNTIL(condition) and FOR EACH item IN aList.

AP pseudocode
total ← 0
REPEAT 4 TIMES
{
    total ← total + 5
}
DISPLAY(total)

total goes 0, 5, 10, 15, 20, and the program displays 20. Four passes or four million passes use the same few lines.

Runs in your browser

All three in one algorithm

Real algorithms mix the three, and the blocks sit inside each other. This one counts the marks that are a pass (50 or more):

AP pseudocode
marks ← [40, 75, 90, 55]
passed ← 0
FOR EACH m IN marks
{
    IF(m ≥ 50)
    {
        passed ← passed + 1
    }
}
DISPLAY(passed)
Part of the codeBuilding blockWhy
All the lines, top to bottomSequencingset up, loop, then display
FOR EACH m IN marksIterationits body runs once for each mark
IF(m ≥ 50)Selectionpassed goes up only for a mark of 50 or more

The IF is inside the loop, so the test is made on every pass. The marks 75, 90 and 55 pass, so the program displays 3. To spot the blocks, look for these words:

Look forBuilding block
Statements one under the otherSequencing
IF and ELSE (Python: if, else)Selection
REPEAT and FOR EACH (Python: for, while)Iteration

These three are enough to build any algorithm.

Check your understanding

What does selection do in an algorithm?

Same job? Comparing two algorithms

Two code segments can look different and still do the same job. The exam often asks, "Do these always give the same result?" You compare two things:

  • the result: what the code displays or returns;
  • the side effect: any change the code leaves behind, such as something displayed, or a variable or list that was changed.

Two segments are the same when, for the same input, both give the same result and the same side effect. Here are three segments. Each starts with a number in x.

AP pseudocode
IF(x > 5)
{
    DISPLAY("big")
}
ELSE
{
    DISPLAY("small")
}
AP pseudocode
IF(x > 5)
{
    DISPLAY("big")
}
IF(x ≤ 5)
{
    DISPLAY("small")
}
AP pseudocode
IF(x ≥ 5)
{
    DISPLAY("big")
}
ELSE
{
    DISPLAY("small")
}

Call them A, B and C. Try three inputs:

xABC
3smallsmallsmall
5smallsmallbig
9bigbigbig

C differs from A at x = 5. One input where they differ is enough to prove two segments are not the same. A and B match every time, and there is a reason: for any number exactly one of x > 5 and x ≤ 5 is true, so exactly one word is displayed, the same word as in A.

Matching on a few inputs proves nothing, because the input that breaks it may be one you did not try. So test the edge values: the number in the condition (5), one above (6), one below (4), zero, and equal values when there are two variables. Then give a reason why every other input behaves the same way.

Runs in your browser

Change x to 4, 5 and 6 and watch when the two answers differ.

Check your understanding

Segment A and segment B each start with n holding a positive whole number.

Segment A:

AP pseudocode
IF(n MOD 2 = 0)
{
    DISPLAY("even")
}
ELSE
{
    DISPLAY("odd")
}

Segment B:

AP pseudocode
IF(n MOD 2 = 0)
{
    DISPLAY("even")
}
IF(n MOD 2 = 1)
{
    DISPLAY("odd")
}

Which statement is true?

The whole unit on one page

This unit fits on one map. Come back to it to see where a lesson belongs.

Algorithms
  • Building algorithms

    • sequencing and selection and iteration
    • reading and drawing flowcharts
    • one algorithm in many forms
  • Evaluating algorithms

    • does it always work?
    • counting the steps
    • reasonable and unreasonable time
  • Linear and binary search

    • look at every item
    • halve the list each time
  • Solving hard problems

    • good enough, fast: heuristics
    • problems no computer can solve
  • Parallel and distributed computing

    • many tasks at once
    • working out the speedup
    • many computers

Common mistakes

  • Thinking the order does not matter. x ← x * 2 then x ← x + 1 is not the same as the reverse.
  • Thinking an IF repeats. An IF runs its block once or not at all. Only a loop repeats.
  • Naming only the outer block. An IF inside a FOR EACH is selection and iteration.
  • Deciding "same" from a few inputs. Try the edge values, and look for a reason that covers every input.
  • Treating two IF blocks like IF and ELSE. They match only when the first block does not change a value that the second test uses.
  • Looking only at the final variables. Something displayed on the way is a side effect too.

On the exam

Expect "Which building blocks does this code use?" and "Which of the following always displays the same thing as the code above?" For the second kind, try the boundary values first. One input where the answers differ rules an option out.

Key words

Sequencing: steps that run one after another, in the order written.

Selection: choosing which steps run, by testing a condition.

Iteration: repeating a group of steps.

Pass: one run through the body of a loop.

Side effect: a change the code makes besides its returned value, such as showing something on the screen or changing a list.

Edge value: an input at the boundary of a condition, such as the number in x > 5, or zero.

AP® is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this site. All lessons and questions here are written by JrCodex.