Find a course

Module 2: Algorithms and ProgrammingLesson 5 of 1113 min

Conditionals, Loops and Tracing

Trace IF and ELSE selection, REPEAT and FOR EACH iteration and Boolean expressions, use MOD and RANDOM, and predict exactly what code will display.

Step 1 of 11Learn

Sequencing, selection and iteration

Every algorithm, no matter how complex, can be built from just three building blocks:

  • Sequencing: running steps in order, one after another.
  • Selection: choosing which steps to run based on a condition (IF).
  • Iteration: repeating steps (loops).

Selection in AP pseudocode:

IF(temperature > 30)
{
  DISPLAY("Hot")
}
ELSE
{
  DISPLAY("Not hot")
}

Conditions are Boolean expressions, which evaluate to true or false. They use the relational operators =, ≠, >, <, ≥, ≤ and the logical operators NOT, AND and OR:

  • a AND b is true only if both are true.
  • a OR b is true if at least one is true.
  • NOT a flips the value.

Ifs can be nested, one inside another, to handle more detailed cases: first check whether a student is enrolled, then, inside that, check their grade.

Order matters in sequencing too. The same three lines in a different order can produce a completely different result, which is exactly why exam questions often show two versions of a code segment that differ only in the order of two lines. Trace both before choosing.

Every algorithm is built from three building blocksAlgorithmSequencingsteps in orderSelectionIF: choose a pathIterationloops: repeat steps

Step 2 of 11Practice · Sort into groups

With age set to 15 and hasTicket set to false, is each expression true or false?

Tap an item, then tap its group (or drag it there).

Step 3 of 11Learn

Three kinds of loops

AP pseudocode has three loop forms.

REPEAT n TIMES runs the body a fixed number of times:

count ← 0
REPEAT 4 TIMES
{
  count ← count + 3
}

After this, count is 12.

REPEAT UNTIL(condition) keeps going until the condition becomes true. It checks the condition before each run, so if the condition is already true, the body never runs:

n ← 1
REPEAT UNTIL(n > 50)
{
  n ← n * 3
}

n goes 1, 3, 9, 27, 81. At 81 the condition is true, so the loop stops. If nothing inside the loop ever makes the condition true, you get an infinite loop.

FOR EACH item IN list visits every element in order, assigning each one to the variable item:

total ← 0
FOR EACH score IN [70, 85, 90]
{
  total ← total + score
}

total ends at 245. FOR EACH is the safest way to process a list, because it can't run past the end.

Notice that REPEAT UNTIL is the opposite of the "while" loop in most languages: while loops run while a condition is true; REPEAT UNTIL runs until it becomes true.

Step 4 of 11Compare

Three AP loops

AspectREPEAT n TIMESREPEAT UNTIL(condition)FOR EACH item IN list
RunsExactly n timesUntil the condition becomes trueOnce per list element
ChecksNothing: counts automaticallyThe condition before each passWhether elements remain
RiskOff-by-one if n is wrongInfinite loop if the condition never becomes trueVery little: cannot run past the end
Example resultcount + 3, 4 times → 12n × 3 from 1 until n > 50 → 81Sum of [70, 85, 90] → 245

Step 5 of 11Practice · Work it out

What does this display? x ← 2, REPEAT UNTIL(x > 40) { x ← x * 2 + 1 }, DISPLAY(x)

Step 6 of 11Learn

MOD and RANDOM

Two operators show up constantly in exam questions.

MOD gives the remainder after division. 17 MOD 5 is 2, because 5 goes into 17 three times with 2 left over. Typical uses:

  • Checking even or odd: n MOD 2 = 0 is true for even numbers.
  • Checking divisibility: year MOD 4 = 0 is part of the leap year rule.
  • Wrapping around: hours on a clock, (hour + 5) MOD 12.

RANDOM(a, b) returns a random whole number from a to b, including both ends. RANDOM(1, 6) simulates a die, and each of the six values is equally likely.

RANDOM powers simulations: programs that model real-world processes, such as traffic, disease spread or a game of chance. Simulations let you run thousands of trials quickly, safely and cheaply, testing ideas you couldn't try in real life. But they're abstractions: they leave out details and rely on assumptions, so their results are only as good as the model. A traffic simulation that ignores weather may predict smooth roads on a snowy morning.

Exam tip: when RANDOM appears in a question, the answer is usually about which outputs are possible or impossible, not about one specific result.

Step 7 of 11Try the calculator

MOD and RANDOM helper

Try different numbers to see the remainder, and how many values RANDOM(a, b) can produce.

n MOD d
2
Possible RANDOM values
6
Chance of any one value
16.7 %

Step 8 of 11Practice · Fill in the blanks

Fill in the blanks

23 MOD 6 = . RANDOM(3, 7) can return different values.

Step 9 of 11Note

Step 10 of 11Practice · Spot the mistake

This procedure should return how many even numbers are in a list. Which lines contain errors?

Step 11 of 11Practice · Code challenge

Write countEven(list) in JavaScript, returning how many numbers in the list are even. JavaScript writes MOD as %, so n % 2 === 0 checks for an even number.

Runs in a sandbox in your browser.
  • countEven([1, 2, 3, 4])
  • countEven([7, 9, 11])
  • countEven([0, 10, -4])
  • countEven([])