Iteration — AP Computer Science A
1. Core Loop Types in Java ★★☆☆☆ ⏱ 5 min
The `while` loop checks its boolean condition *before* executing the loop body, so it runs 0 or more times. It is best used when the number of iterations is unknown before the loop starts, such as processing input until a sentinel value. Syntax: `while (booleanCondition) { // loop body }`
The `for` loop bundles initialization, condition check, and counter update into a single line, optimized for when the number of iterations is known in advance. It is the most commonly tested loop on the AP CS A exam, especially for array traversal. Syntax: `for (initialization; booleanCondition; update) { // loop body }`
The `do-while` loop checks its condition *after* executing the loop body, meaning it always runs at least 1 time, even if the condition is initially false. It is almost exclusively used for input validation on the AP exam. Syntax: `do { // loop body } while (booleanCondition);`
Exam tip: `do-while` loops appear in only ~5% of AP CS A loop questions, almost always for input validation.
2. Nested Loops ★★★☆☆ ⏱ 5 min
A nested loop is a loop placed inside the body of another loop. The inner loop completes all of its iterations for every single iteration of the outer loop, making it ideal for processing multi-dimensional data like 2D arrays.
Exam tip: Nested loops are a core component of FRQ 4 (2D Arrays) on the AP exam. Practice traversing irregular 2D arrays (rows of different lengths) as well as square grids. The time complexity of a nested loop is $O(n \times m)$, where $n$ is outer iterations and $m$ inner iterations.
3. Common Loop Counter Patterns ★★☆☆☆ ⏱ 4 min
Standardized loop counter patterns solve common programming tasks and appear in almost every AP CS A loop question. The most frequently tested patterns are:
- **Fixed zero-based traversal**: Access all elements of a zero-indexed array/ArrayList: `for (int i = 0; i < arr.length; i++) { process arr[i]; }`
- **Reverse traversal**: Process elements from last to first (e.g. reversing an array): `for (int i = arr.length - 1; i >= 0; i--) { process arr[i]; }`
- **Step iteration**: Access every k-th element in a sequence: `for (int i = 0; i <= 10; i += 2) { print i; }`
- **Counter accumulation**: Count occurrences of a condition: `int count = 0; for (int i=1; i<=20; i++) { if (i%2 == 0) count++; }` (counts 10 even numbers 1-20)
Exam tip: A common trap for reverse traversal is starting the counter at `arr.length` instead of `arr.length - 1`, which causes an `ArrayIndexOutOfBoundsException`.
4. Manual Loop Tracing & Off-by-One Errors ★★★☆☆ ⏱ 9 min
Manual loop tracing is a critical skill for AP CS A multiple-choice questions, where you must predict output or final variable values without a compiler. Follow these steps for accurate results:
- Write down all initial variable values before the loop starts
- Check the loop condition first; exit immediately if false
- Execute each line of the body in order, updating variables
- Record any printed output
- Repeat until the condition evaluates to false
Off-by-one (OBO) errors are logic errors where a loop runs one time too many or one time too few. They cause ~20% of lost points on loop-related AP CS A questions, and most often stem from incorrect condition operators, wrong counter initialization, or incorrect updates.
Exam tip: After writing any loop, test the first and last iteration: confirm the first and last counter values are valid for your required bounds.
Common Pitfalls
Why: Students focus on writing the loop body first and overlook the update step, leading to an infinite loop.
Why: Floating-point precision errors make exact matches extremely unlikely, leading to unexpected early termination or infinite loops.
Why: This breaks the `for` loop's controlled flow, leading to unexpected iteration counts when students try to dynamically skip iterations.
Why: Using generic variable names like `i` and `j` leads to confusion between row and column indices, causing errors.
Why: Students default to `do-while` for all input processing, even when input is already pre-validated, leading to unnecessary extra execution.