| Study Guides
AP · Iteration · 18 min read · Updated 2026-05-07

Iteration — AP Computer Science A CS A Study Guide

For: AP Computer Science A candidates sitting AP Computer Science A.

Covers: All core iteration subtopics for AP CS A including while/for/do-while loops, nested loops, loop counter patterns, manual loop tracing, and off-by-one error mitigation.

You should already know: Basic Java or any other procedural-language programming.

A note on the practice questions: All worked questions in the "Practice Questions" section below are original problems written by us in the AP Computer Science A style for educational use. They are not reproductions of past College Board papers and may differ in wording, numerical values, or context. Use them to practise the technique; cross-check with official College Board mark schemes for grading conventions.


1. What Is Iteration?

Iteration (commonly called looping) is the repeated execution of a block of code until a predefined termination condition is met. It is one of the three core control structures in programming (alongside sequence and selection) and makes up 10–15% of the AP CS A exam content, appearing frequently in both multiple-choice questions and free-response questions (FRQs) focused on array, ArrayList, and 2D array manipulation. Unlike hardcoding repeated operations, loops make code shorter, easier to modify, and less prone to human error.

2. while, for, do-while loops

Java provides three core loop types, each designed for specific use cases:

while loop

The while loop checks its boolean condition before executing the loop body, so it runs 0 or more times. Syntax:

while (booleanCondition) {
 // loop body
}

Worked example: Sum all integers from 1 to 5:

int sum = 0;
int i = 1;
while (i <= 5) {
 sum += i;
 i++; // critical update step to avoid infinite loops
}
// Final sum = 15

Use while loops for cases where the number of iterations is unknown before the loop starts (e.g., processing user input until a sentinel value is entered).

for loop

The for loop is optimized for cases where the number of iterations is known in advance. It bundles initialization, condition check, and counter update into a single line. Syntax:

for (initialization; booleanCondition; update) {
 // loop body
}

Worked example: Same sum operation as above, rewritten with a for loop:

int sum = 0;
for (int i = 1; i <=5; i++) {
 sum +=i;
}
// Final sum =15

This is the most commonly tested loop type on the AP CS A exam, especially for array traversal.

do-while loop

The do-while loop checks its boolean condition after executing the loop body, so it runs at least 1 time, even if the condition is initially false. Syntax:

do {
 // loop body
} while (booleanCondition);

Worked example: Prompt a user for a positive integer, repeating until valid input is received:

int num;
Scanner sc = new Scanner(System.in);
do {
 System.out.print("Enter a positive number: ");
 num = sc.nextInt();
} while (num <= 0);

Exam tip: do-while loops appear in ~5% of loop questions, almost exclusively for input validation use cases.

3. Nested loops

A nested loop is a loop placed inside the body of another loop. The inner loop runs its full set of iterations for every single iteration of the outer loop, making it ideal for working with multi-dimensional data like 2D arrays or grid patterns. Worked example 1: Print a 3x3 grid of asterisks:

for (int row = 0; row < 3; row++) { // outer loop runs 3 times
 for (int col = 0; col <3; col++) { // inner loop runs 3 times per outer iteration
 System.out.print("* ");
 }
 System.out.println(); // move to next row
}

Output:

* * * 
* * * 
* * * 

Worked example 2: Calculate the sum of all elements in a 2D array:

int[][] scores = {{85, 92, 78}, {90, 87, 93}, {76, 89, 91}};
int total = 0;
for (int r = 0; r < scores.length; r++) { // iterate over rows
 for (int c = 0; c < scores[r].length; c++) { // iterate over columns in current row
 total += scores[r][c];
 }
}
// Final total = 781

Exam tip: Nested loops are a staple of FRQ 4 (2D Arrays) on the AP exam, so practice traversing irregular 2D arrays (where rows have different lengths) as well as square grids. The time complexity of a nested loop is , where is the number of outer loop iterations and is the number of inner loop iterations.

4. Loop counter patterns

Loop counter patterns are standardized uses of loop variables to solve common programming tasks, and they appear in almost every AP CS A loop question:

1. Fixed zero-based traversal

Used to access all elements of an array or ArrayList, which use zero-based indexing:

// Traverse all elements of array arr of length N
for (int i = 0; i < arr.length; i++) {
 // process arr[i]
}

2. Reverse traversal

Used to process elements from last to first, e.g., reversing an array:

for (int i = arr.length - 1; i >= 0; i--) {
 // process arr[i]
}

Exam tip: A common trap is starting the reverse loop at arr.length instead of arr.length -1, which causes an ArrayIndexOutOfBoundsException.

3. Step iteration

Used to access every k-th element in a sequence:

// Print all even numbers from 0 to 10
for (int i =0; i <=10; i += 2) {
 System.out.print(i + " ");
}
// Output: 0 2 4 6 8 10

4. Counter accumulation

Used to count occurrences of a specific condition:

// Count number of even numbers between 1 and 20
int count =0;
for (int i=1; i<=20; i++) {
 if (i % 2 == 0) count++;
}
// Final count =10

5. Tracing loops by hand

Manual loop tracing is a critical skill for the AP CS A multiple-choice section, where you will be asked to predict the output or final value of variables after a loop runs, without access to a compiler. Follow these steps for accurate tracing:

  1. Write down all initial variable values before the loop starts
  2. Check the loop condition first: if false, exit immediately
  3. Execute each line of the loop body in order, updating variable values as you go
  4. Record any printed output
  5. Repeat until the loop condition evaluates to false Worked example: Trace the following code to find its output:
int x = 2;
int y =0;
while (x <7) {
 y +=x;
 x +=2;
 System.out.print(y + " ");
}

Tracing steps:

  • Initial values: ,
  • Iteration 1: Condition = true: , , output 2
  • Iteration 2: Condition = true: , , output 6
  • Iteration 3: Condition = true: , , output 12
  • Iteration 4: Condition = false: exit loop Final output: 2 6 12 Exam tip: Never trace loops in your head; always write down variable values step by step, even for short loops. Examiners intentionally add distractors that correspond to common tracing mistakes like skipping an iteration or miscalculating an update.

6. Off-by-one errors

Off-by-one (OBO) errors are logic errors where a loop runs one time too many or one time too few, and they are responsible for ~20% of lost marks on loop-related AP CS A questions. They occur most often due to:

  1. Incorrect condition operators (using < instead of <= or vice versa)
  2. Wrong initialization of the loop counter
  3. Incorrect update step for the counter Example 1: Loop runs one time too few: Intended behavior: Sum integers from 1 to 10 (expected result 55) Faulty code:
int sum =0;
for (int i=1; i<10; i++) sum +=i;
// Actual sum =45 (sums 1 to 9, misses 10)

Fix: Change the condition to i<=10 Example 2: Loop runs one time too many: Intended behavior: Traverse all elements of an array of length 5 (indices 0-4) Faulty code:

for (int i=0; i<=5; i++) System.out.print(arr[i]);
// Throws ArrayIndexOutOfBoundsException when i=5

Fix: Change the condition to i<5 or i<=4 Exam tip: After writing any loop, test the first and last iteration: confirm the first counter value is valid, and the last counter value hits exactly the upper or lower bound you need.

7. Common Pitfalls (and how to avoid them)

  • Pitfall: Forgetting to update the loop counter in a while loop, leading to an infinite loop. Why students do it: They focus on writing the loop body first and overlook the update step. Correct move: Write the counter update line immediately after writing the while condition, before filling in the rest of the loop body.
  • Pitfall: Using == to compare floating-point values in loop conditions, leading to unexpected early termination or infinite loops. Why: Floating-point precision errors make exact matches extremely unlikely. Correct move: Use a tolerance threshold, e.g., while (Math.abs(x - target) < 0.001) instead of while (x == target).
  • Pitfall: Modifying the for loop counter inside the loop body, leading to unexpected iteration counts. Why: Students try to skip iterations dynamically, breaking the for loop's controlled flow. Correct move: Adjust the step size in the for loop's update clause, or use a while loop if you need dynamic counter changes.
  • Pitfall: Mixing up the order of nested loops for 2D array traversal, leading to incorrect processing order or index out-of-bounds errors. Why: Students use generic i and j variable names instead of descriptive labels. Correct move: Name nested loop variables row and col when working with 2D arrays to eliminate confusion.
  • Pitfall: Using a do-while loop when the loop may need to run 0 times. Why: Students default to do-while for all input processing, even when input is pre-validated. Correct move: Ask "does this code need to run at least once?" If the answer is no, use a while loop instead.

8. Practice Questions (AP Computer Science A Style)

Question 1

What is the output of the following code snippet?

int a = 1;
int b = 0;
do {
 b += 3;
 a += 2;
} while (a < 6);
System.out.println(b);

A) 3 B) 6 C) 9 D) 12 Solution: The do-while runs first before checking the condition:

  1. Iteration 1: , , condition = true
  2. Iteration 2: , , condition = true
  3. Iteration 3: , , condition = false Final output is 9. Correct answer: C

Question 2

Which code snippet correctly counts the number of elements in an int array arr that are greater than 10? A) int count=0; for(int i=0; i<=arr.length; i++) { if(arr[i]>10) count++; } B) int count=0; for(int i=0; i<arr.length; i++) { if(arr[i]>10) count++; } C) int count=0; for(int i=1; i<arr.length; i++) { if(arr[i]>10) count++; } D) int count=0; int i=0; while(i<arr.length) { if(arr[i]>10) count++; } Solution: A has an off-by-one error (accesses invalid index arr.length), C skips the first element (index 0), D forgets to increment i leading to an infinite loop. Correct answer: B

Question 3

What is the value of sum after the following code executes?

int sum = 0;
for (int i=0; i<3; i++) {
 for (int j=0; j<=i; j++) {
 sum += i * j;
 }
}

Solution: Trace the nested loops step by step:

  1. Outer loop : inner loop runs for only: sum += , sum = 0
  2. Outer loop : inner loop runs for : sum += , sum = 1
  3. Outer loop : inner loop runs for : sum += , sum = 7 Final sum: 7

9. Quick Reference Cheatsheet

Loop Type Syntax Execution Count Primary Use Case
while while(condition) { body } 0 or more Unknown number of iterations, no guaranteed run
for for(init; condition; update) { body } 0 or more Known number of iterations, array traversal
do-while do { body } while(condition); 1 or more Input validation, guaranteed minimum 1 run
Common Pattern Code Snippet
Zero-based array traversal for(int i=0; i<arr.length; i++)
Reverse array traversal for(int i=arr.length-1; i>=0; i--)
Step iteration (every k-th value) for(int i=0; i<=n; i+=k)
Off-by-one Error Check Correct Condition
Sum integers 1 to N i <= N
Traverse array of length N i < N
Last valid array index i == arr.length - 1

Loop Tracing Steps: 1. Record initial values → 2. Check condition → 3. Update variables → 4. Record output → 5. Repeat until condition fails

10. What's Next

Iteration is a foundational building block for almost all remaining AP CS A topics. You will use loops extensively for array and ArrayList manipulation (Unit 6), 2D array processing (Unit 8), String operations (Unit 2), and sorting/searching algorithms (Unit 7) like insertion sort, selection sort, and linear/binary search. Mastering iteration now will save you significant time when you learn these more complex topics, as 70% of FRQ questions require at least one loop to solve. You will also encounter loops when working with recursive algorithms later in the course, as iteration and recursion are two different approaches to solving repeated-execution problems.

If you have any questions about loop syntax, tracing, or common errors, you can ask Ollie, our AI tutor, for personalized practice problems or step-by-step explanations tailored to your weak spots. You can also find more AP CS A study materials and full-length practice tests on the homepage to reinforce your iteration skills before moving on to the next unit on arrays.

← Back to topic

Stuck on a specific question?
Snap a photo or paste your problem — Ollie (our AI tutor) walks through it step-by-step with diagrams.
Try Ollie free →