Loops

AP Computer Science A · Unit 2: Control flow

Loops notes

Fact-checked by a second, independent AI review.

Loops repeat a block of code until a condition stops them. Be fluent with for, while, and do-while loops, and how to count, accumulate, and handle termination correctly.

for loop
Initialises a control variable, tests a condition, and updates the variable each iteration; ideal for counting from a start value to an end value.
while loop
Checks the condition before each iteration; may require pre-iteration setup to ensure the loop runs correctly.
do-while loop
Executes the body once, then tests the condition; guarantees at least one execution.
loop control variable
The variable that tracks progress toward termination; must be updated properly to avoid infinite loops.
common loop patterns
Patterns include counting, summing, and finding extremes; use an accumulator and adjust the update step to avoid off-by-one errors.
nested loops
One loop inside another; affects time complexity and output structure; clarify what the inner loop does for each outer iteration.

Remember it: For, While, Do-While — Java loops.

Exam tip: AP CSA examiners look for correct loop structure, clear termination conditions, proper updates to the loop variable, and avoidance of off-by-one errors; also expect correct use of accumulators and awareness of nested loop effects on complexity.

Syllabus checklist

  • Loops: core ideas
  • Terms and typical exam questions for "Control flow" in AP Computer Science A (Java
  • College Board)

Practice questions

  1. 1. Which loop repeats with an automatic update in its header?

    Answer checked

    Show answer

    Answer: for. A for loop includes an update expression in its header, e.g., for(i=0; i<n; i++).

  2. 2. What is the sum after this loop? int sum=0; for(int i=1;i<=3;i++) sum+=i;

    Answer checked

    Show answer

    Answer: 6. Sum 1+2+3 = 6.

  3. 3. A loop that always executes its body at least once is a ____ loop.

    Answer checked

    Show answer

    Answer: do-while. Do-while loops run once before checking the condition.

  4. 4. A while loop may not execute if its condition is false initially.

    Answer checked

    Show answer

    Answer: True. If the condition is false at the start, the body does not execute.

  5. 5. Starting with n = 7, how many iterations does this run? int c=0; while(n>0){ c++; n-=2; }

    Answer checked

    Show answer

    Answer: 4. Iterations when n = 7,5,3,1 → 4 iterations.

Practise loops as a game

Hearts, combos, streaks and an AI tutor that explains every answer. Start free.

Start free

More from Unit 2: Control flow