The examples below use AP CSP Pseudocode. For similar loops in Java, see while and for loops.

IF statement (not a loop)

n ← 1

IF(n ≤ 5)
{
    DISPLAY(n)
    n ← n + 1
}

DISPLAY("n outside")
DISPLAY(n)

The code segment displays:

1 n outside 2 

The condition for an IF statement is checked when the statement is reached. If the condition evaluates to true, the code inside the body of the statement runs once.

REPEAT UNTIL statement (a loop)

n ← 1

REPEAT UNTIL(n > 5)
{
    DISPLAY(n)
    n ← n + 1
}

DISPLAY("n outside")
DISPLAY(n)

The code segment displays:

1 2 3 4 5 n outside 6 

The only changes from the earlier code segment are:

The condition for a REPEAT UNTIL loop is checked before the first execution, the same as an IF statment. If the condition evaluates to false, the body of the loop executes (the opposite of an IF statement).

When the body finishes executing, the condition is checked again. If the condition evaluates to false again, the body executes again. The process repeats until:

REPEAT UNTIL loop termination

A REPEAT UNTIL loop terminates when the condition is checked and evaluates to true, not as soon as the condition would evaluate to true. The example below shows the difference.

n ← 1

REPEAT UNTIL(n > 5)
{
    n ← n + 1
    DISPLAY(n)
}

DISPLAY("n outside")
DISPLAY(n)

The code segment displays:

2 3 4 5 6 n outside 7 

The value of n becomes 6 during the last execution. This does not immediately cause the loop to terminate. The value 6 is displayed before the condition is checked again.

REPEAT n TIMES loop

count ← 1

REPEAT 3 TIMES
{
    count ← count + 1
}

DISPLAY("count")
DISPLAY(count)

The code segment displays:

count 3 

The code in the loop body runs the specified number of times.

REPEAT n TIMES loop with variable

runs ← 5

REPEAT runs TIMES
{
    DISPLAY(runs)
}

DISPLAY("runs outside")
DISPLAY(runs)

The code segment displays:

5 5 5 5 5 runs outside 5 

The number of times the loop runs can be an integer literal (the previous example) or an integer variable (this example). The control variable does not need to be named n.

If a variable is used to control the number of times the loop runs, the variable’s value does not change.

Undefined REPEAT n TIMES loop

runs ← 5

REPEAT runs TIMES
{
    DISPLAY(runs)
    runs ← runs + 1
}

DISPLAY("runs outside")
DISPLAY(runs)

This loop’s behavior is undefined in AP CSP Pseudocode. The value of the control variable is changed. Although this is valid (and important) in a REPEAT UNTIL loop, it is not valid in a REPEAT n TIMES loop.

Loops with this behavior will not appear on the AP CSP Exam.

FOR EACH item IN aList loops

FOR EACH item IN aList loops can be used to loop through lists.

Help & comments

Get help from AP CS Tutor Brandon Horn

Comment on REPEAT Loops in AP CSP Pseudocode