impera Open Impera

AP Computer Science Principles · Algorithms and programming

Conditionals and iteration

1Sequencing, selection and iteration

Every algorithm can be built from three structures:

  • Sequencing: steps run in order.
  • Selection: a condition decides which steps run (IF / ELSE).
  • Iteration: steps repeat (REPEAT loops).

The order of statements matters: the same statements in a different order can give a different result.

Check yourself

Which structure makes a decision based on a condition?

  • Iteration

  • Selection

  • Sequencing

  • Abstraction

Show the answer

Selection

IF statements.

2Boolean expressions and conditionals

Boolean expressions evaluate to true or false using relational operators =, ≠, <, >, ≤, ≥ and logical operators NOT, AND, OR.

IF (temp > 30 AND NOT raining)
{
   DISPLAY ("Go to the beach")
}
ELSE
{
   DISPLAY ("Stay in")
}

Nested conditionals put one IF inside another to test several conditions in sequence.

Worked example

a ticket price.

  1. IF age < 12 → price 5.
  2. ELSE IF age ≥ 65 → price 6.
  3. ELSE → price 10. (In AP pseudocode, the ELSE IF is written as a nested IF inside the ELSE block.)
Check yourself

For a ← 4, b ← 9, what is (a > 5) OR (b > 5)?

  • true

  • false

  • 9

  • An error

Show the answer

true

One side true is enough.

3Iteration

AP pseudocode loops:

REPEAT n TIMES
{
   <block>
}

REPEAT UNTIL (condition)
{
<block>
}

  • REPEAT n TIMES runs exactly n times.
  • REPEAT UNTIL (condition) checks the condition before each pass and stops when it becomes true; if it is already true, the block runs zero times.
  • If the condition never becomes true, the result is an infinite loop.
Worked example

double a number until it exceeds 100.

n ← 3
REPEAT UNTIL (n > 100)
{
   n ← n * 2
}

n goes 3, 6, 12, 24, 48, 96, 192, then stops: 6 passes, final value 192.

REPEAT UNTIL stops as soon as its condition becomes true

Check yourself

REPEAT UNTIL (count = 5) stops when:

  • Never

  • count equals 5

  • count is not 5

  • After exactly 5 passes always

Show the answer

count equals 5

Until the condition is true.

4Combining loops and conditions

Many algorithms put a conditional inside a loop:

total ← 0
REPEAT UNTIL (LENGTH(nums) = 0)
{
   IF (nums[1] MOD 2 = 0)
   {
      total ← total + nums[1]
   }
   REMOVE (nums, 1)
}

This adds the even numbers, removing each element after looking at it.

Equivalent algorithms can be written in different ways: with different loops or conditions, they still produce the same result for all inputs.

Check yourself

How many times does REPEAT 4 TIMES { REPEAT 3 TIMES { DISPLAY ("*") } } display a star?

  • 7

  • 4

  • 12

  • 3

Show the answer

12

4 × 3.

5Going deeper: nested conditions, loops that may never run, and robot questions

Three building blocks make up every algorithm: sequencing (steps in order), selection (choosing which steps to run) and iteration (repeating steps).

Selection

IF (condition)
{
    statements
}
ELSE
{
    other statements
}

Boolean operators

  • NOT condition: true when the condition is false.
  • a AND b: true only when both are true.
  • a OR b: true when either or both are true.

Worked example (evaluate): with age = 16 and hasPermit = true, evaluate (age ≥ 18) OR (hasPermit AND age ≥ 16).

  1. age ≥ 18 is false.
  2. hasPermit AND age ≥ 16 is true AND true = true.
  3. false OR true = true.

Nested conditionals: a conditional inside another.

IF (score ≥ 90)
{
    DISPLAY("A")
}
ELSE
{
    IF (score ≥ 80)
    {
        DISPLAY("B")
    }
    ELSE
    {
        DISPLAY("C")
    }
}

For score = 85: the first condition is false, so the ELSE runs; inside it, 85 ≥ 80 is true: displays B. Exactly one letter is displayed for any score.

Equivalent conditions: IF (a) { IF (b) { S } } behaves like IF (a AND b) { S }. And NOT (a AND b) is the same as (NOT a) OR (NOT b).

Iteration

REPEAT n TIMES: a fixed number of repetitions.

REPEAT UNTIL (condition): repeat until the condition becomes true.

  • The condition is tested before each pass.
  • If it is true at the start, the body runs zero times.
  • If it never becomes true, the loop is infinite.

Worked example (trace):

n ← 1
REPEAT UNTIL (n > 20)
{
    n ← n * 3
}
DISPLAY(n)
  1. n = 1: not > 20; n becomes 3.
  2. n = 3: becomes 9.
  3. n = 9: becomes 27.
  4. n = 27: the condition is true; stop.
  5. Displays 27.

Worked example (zero passes):

count ← 10
REPEAT UNTIL (count ≥ 5)
{
    count ← count + 1
}

The condition is already true, so the body never runs; count stays 10.

Worked example (infinite loop):

k ← 1
REPEAT UNTIL (k = 10)
{
    k ← k + 2
}

k takes 1, 3, 5, 7, 9, 11 …: it skips 10, so the loop never ends. Using k ≥ 10 would fix it.

Combining loops and conditions: count the even numbers from 1 to 10.

count ← 0
n ← 1
REPEAT 10 TIMES
{
    IF (n MOD 2 = 0)
    {
        count ← count + 1
    }
    n ← n + 1
}

count ends as 5.

Robot questions: a robot (a triangle) moves on a grid.

  • MOVE_FORWARD(): one square in the direction it faces. Moving into a wall or off the grid is an error.
  • ROTATE_LEFT() and ROTATE_RIGHT(): turn 90° in place, without moving.
  • CAN_MOVE(direction): true if the square in that direction (forward, left, right or backward) is open.
Worked example

a robot faces right at the left end of a row of five open squares.

REPEAT UNTIL (NOT CAN_MOVE(forward))
{
    MOVE_FORWARD()
}
ROTATE_LEFT()
  1. It moves forward four times, reaching the right-hand end.
  2. CAN_MOVE(forward) is then false, so the loop stops.
  3. It rotates left and now faces up.

To answer robot questions, trace on the grid with your pencil, tracking position and direction after every command. Remember that turning does not move the robot.

Common mistakes

  • Reading REPEAT UNTIL as "repeat while."
  • Assuming the body always runs at least once.
  • Missing that a counter can jump past the stopping value.
  • Treating a nested conditional as separate independent tests.
  • Moving the robot when it rotates, or confusing its left with the page's left.
Check yourself

How many times does the body run? t ← 0, then REPEAT UNTIL (t ≥ 12) { t ← t + 5 }.

  • 2

  • 12

  • 4

  • 3

Show the answer

3

t becomes 5, 10, then 15; the condition is then true.

6For top marks

  • Trace REPEAT UNTIL carefully: the condition is checked before each pass and the loop stops when it is true.
  • Use De Morgan's laws to rewrite NOT (a AND b) as NOT a OR NOT b.
  • For "which code segments produce the same result" questions, test each with two or three inputs, including boundary values.
  • Make sure loops change something that eventually ends them.
Example

NOT (x > 5 OR y < 2) is equivalent to x ≤ 5 AND y ≥ 2.

Check yourself

Which is equivalent to NOT (a AND b)?

  • a OR b

  • (NOT a) OR (NOT b)

  • (NOT a) AND (NOT b)

  • NOT a AND b

Show the answer

(NOT a) OR (NOT b)

De Morgan.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera