AP® Computer Science Principles · Big Idea 3 · Topic 3.8

REPEAT n TIMES

REPEAT n TIMES runs a block of code exactly n times, then stops and moves to the next line. It saves you from writing the same instruction over and over.

Copying a step forty times is slow to write, easy to get wrong, and hard to fix — change one thing and you have to change it in forty places. A loop fixes this by writing the step once and telling the program how many times to run it. REPEAT n TIMES is the simplest version: it names a count, n, and runs its body that many times, no more, no less.

Mechanically, REPEAT n TIMES keeps an internal count of how many passes it has done. Before each pass it checks whether that count has reached n. If not, it runs the body once and adds one to the count. Once the count equals n, the loop stops and the program moves on to whatever comes after it. No condition on the data is checked, just the number of passes — that is what separates REPEAT n TIMES from a conditional loop like REPEAT UNTIL.

This matters for what comes next in the unit because REPEAT n TIMES is the bridge between straight-line code and the more flexible loops. REPEAT UNTIL and general iteration statements run until some condition on the data becomes true, which might take an unknown number of passes or even never finish. REPEAT n TIMES always finishes after a fixed, countable number of steps, which makes it the natural tool for traversing a list of known length or repeating an action a set number of times, and a stepping stone toward thinking about how many steps an algorithm takes.

Key terms

REPEAT n TIMES
A loop structure that runs its body exactly n times, where n is fixed before the loop starts running.
Iteration
One complete run through the body of a loop, also called a pass.
Loop body
The block of instructions inside the loop that gets repeated.
REPEAT UNTIL
A loop that keeps running until a condition on the data becomes true, rather than a fixed number of times.

Watch it explained

  1. How it worksHow does REPEAT n TIMES run its block exactly n times and then move on?
  2. Worked exampleTrace a REPEAT 4 TIMES loop that starts total at 0 and adds 3 on each pass.
  3. Going furtherWhat happens when the repeat count is a variable that gets changed during the run?
  4. Common mistakeWhy doesn't a loop set to repeat 5 times run its body 6 times?

Check yourself

Your turn1 of 2
A REPEAT 35 TIMES loop starts total at 0 and adds 13 on each pass. What value does total hold when the loop finishes?

End of topic.