AP Computer Science Principles · Unit 3: Algorithms & Programming
3.8 Iteration
What is iteration?
Iteration is repeating a set of instructions until a condition is met, using loops. This avoids rewriting the same code repeatedly. Two common loop types are the for loop (repeats a set number of times) and the while loop (repeats as long as a condition is true, useful when the number of repetitions is unknown).
Loop structure and control
A loop needs an initialization, a condition checked each pass, and an update that changes a variable, otherwise it can run forever (an infinite loop). The loop variable tracks progress. Each repetition is called an iteration, and the loop body executes only while the condition evaluates to true.
Iteration and program behavior
Iteration lets algorithms process collections of data, like adding up a list or searching through items, without knowing the exact size in advance. Combined with selection (conditionals) inside the loop body, iteration allows programs to make repeated decisions, producing complex behavior from simple, reusable code.
Key terms
- Iteration
- The process of repeating a set of instructions using a loop until a condition is met.
- For loop
- A loop used to repeat instructions a specific, known number of times.
- While loop
- A loop that repeats as long as a given condition remains true.
- Infinite loop
- A loop that never terminates because its condition never becomes false.
- Loop variable
- A variable that tracks progress through a loop, often updated each iteration to control when the loop ends.
Try an AP-style question
Code
x ← 1
REPEAT 4 TIMES
{
x ← x * 2
}What is x?
- 4
- 8
- 32
- 16
Show the answer
D. 1 → 2 → 4 → 8 → 16.
Practice 8 AP-style questions with instant explanations, flashcards and spaced review.
Study 3.8 free in APrep