Iteration, Loops, and Nested Loops – AP CS A, Unit 4 – Study Notes
offline

Source: Princeton Review AP CS A Prep, 8th Edition

Tags: for loop, while loop, nested loops, loop tracing, iteration, string traversal, pattern printing, counting iterations, AP Computer Science A, Unit 4

Difficulty: Intermediate Prerequisites: Java Fundamentals (expressions, types, conditionals, String methods).


Big Picture

Iteration is where Java programs start doing real work. Once you can evaluate expressions and branch with conditionals, loops let you repeat operations over data, build up results, and traverse structures. The AP exam tests your ability to trace loops precisely, count iterations, predict output from nested loops, and choose the correct loop structure for a given task. About a quarter of the multiple-choice questions on a typical exam involve loop tracing, and every free-response question uses iteration in some form. If you can trace a nested loop without losing your place, you are in good shape.


TL;DR

for loops are best when you know how many times to iterate. while loops are best when the stopping condition depends on runtime values. Nested loops multiply their iteration counts. The exam expects you to trace through loops by hand, tracking every variable change, and to recognise common patterns like accumulation, counting, and string reversal.


Key Terms

for loop

A loop with initialisation, condition, and update all in one line: for (int i = 0; i < n; i++). Runs the body as long as the condition is true, executing the update after each iteration.

while loop

A loop that repeats as long as its condition is true. The programmer is responsible for initialising and updating the loop variable separately. Easy to create infinite loops if the update is forgotten.

Nested loop

A loop inside another loop. The inner loop completes all its iterations for each single iteration of the outer loop. If the outer runs m times and the inner runs n times, the body executes m * n times.

Loop variable (iterator)

The variable that controls progression through the loop, typically i, j, or k. Its scope in a for loop is limited to the loop itself.

Accumulator pattern

Using a variable (often sum or count) initialised before the loop, then updated inside the loop body to build up a result.

Off-by-one error

A mistake where a loop runs one time too many or one time too few. Often caused by confusing < with <=, or starting at 0 instead of 1.

String traversal

Iterating through a string character by character (or substring by substring) using indices from 0 to length() - 1.


Core Content

For Loop Mechanics

  • Execution order: initialise, check condition, execute body, update, check condition, execute body, update, ...

  • The loop ends when the condition evaluates to false.

  • for (int i = 1; i < 2; i++) runs once (i = 1 only). for (int i = 1; i <= 2; i++) runs twice (i = 1, 2). Watch the boundary.

While Loop Mechanics

  • The condition is checked before each iteration, including the first. If the condition is false from the start, the body never executes.

  • To reverse a string using a while loop, start i at str.length() - 1 and decrement with i--, using while (i >= 0).

    • Starting at str.length() without subtracting 1 causes an IndexOutOfBoundsException on the first substring call if you try to access index length().

    • Using while (i > 0) instead of while (i >= 0) misses the character at index 0.

Nested Loop Counting

  • For triple-nested loops like for (i = 1; i < 2; i++) / for (j = 1; j <= 3; j++) / for (k = 1; k < 4; k++), count the iterations of each: outer runs 1 time, middle runs 3 times, inner runs 3 times. Total body executions: 1 3 3 = 9. Accumulate i j k across all iterations to find the sum.

Nested Loop Output Patterns

  • Pattern-printing questions (e.g., printing triangles of asterisks) combine an outer loop over rows with an inner loop over columns.

  • The inner loop's bounds often depend on the outer loop variable, creating a shrinking or growing pattern.

  • Spaces before symbols create right-aligned patterns. The number of spaces typically equals num - i or similar.

String Traversal with Nested Loops

  • Iterating through substrings of decreasing length (e.g., printing "map", "ma", "m", then "ap", "a", then "p") uses an outer loop for the starting index and an inner loop for the ending index.

  • s.substring(j, k) where k starts at s.length() and decreases to j + 1 (or j) produces substrings of shrinking length from each starting position.

Loop Tracing with Conditionals

  • When a loop body contains an if statement, the condition may cause the body to behave differently on different iterations.

  • Example: for (int j = 1; j < 4; j++) with if (x != 0 && j / x > 0) requires you to track x across iterations. If x is 0, the && short-circuits and the division never happens (no ArithmeticException).

  • When x is 0, j / x is never evaluated. The else branch runs, printing j x = j 0 = 0.

Counting Iterations in Algorithms

  • For a pair of nested loops where outer runs p from 1 to n - 1 and inner runs q from 1 to n, the inner body runs (n - 1) * n times. This is the pattern behind selection sort and similar O(n^2) algorithms.


Formulas / Diagrams

Nested loop iteration count: If the outer loop runs a times and the inner loop runs b times per outer iteration, the inner body runs a * b times total.

Accumulator sum for i j k with triple nesting: Sum = (sum of i values) (sum of j values) (sum of k values), but only when the expression is a product of independent loop variables. Otherwise, trace manually.


Real-World Applications

Nested loops power image processing (iterating over pixels in rows and columns), matrix multiplication, and search algorithms. Pattern-printing exercises, while they seem academic, build the spatial reasoning needed to generate reports, format output tables, and lay out UI grids.


Common Misconceptions

  • Students often assume that changing a for-each loop variable (like element *= 2 inside for (int element : arr)) modifies the original array. It does not. The loop variable is a local copy of each element.

  • Forgetting that for (int i = 0; i < str.length(); i++) visits every index from 0 to length() - 1, while for (int i = str.length() - 1; i >= 0; i--) visits the same indices in reverse. Using i > 0 in the reverse version misses index 0.

  • Miscounting nested loop iterations by adding instead of multiplying. If the outer runs 3 times and the inner runs 4 times, the body runs 12 times, not 7.

  • Assuming short-circuit evaluation prevents all runtime errors. It only prevents evaluation of the right-hand operand; it does not fix logic errors elsewhere in the loop.


Why It Matters / Exam Flags

⚠️ Loop tracing with pen and paper is the single most reliable skill for the multiple-choice section. There is no shortcut; trace every iteration.

⚠️ Nested loop output questions (pattern printing) appear frequently. Identify the outer loop as rows, the inner as columns, and track what gets printed vs. what triggers a newline.

⚠️ The for-each loop does not modify the underlying array or list. This is tested both directly ("what is the output?") and indirectly ("which code achieves the desired result?").

⚠️ Off-by-one errors in loop bounds are a favourite source of wrong answer choices. Always check whether the loop should use < or <=, and whether to start at 0 or 1.


Quick Self-Test

  1. True or false: for (int i = 0; i < 5; i++) runs the body 5 times.

  1. Fill in the blank: In a nested loop where the outer runs 3 times and the inner runs 4 times per outer iteration, the inner body executes ______ times total.

  1. True or false: Modifying the loop variable inside a for-each loop changes the original array element.

  1. Fill in the blank: To traverse a string in reverse, start i at str.length() - 1 and loop while i ______ 0.

  1. True or false: If x == 0, the expression x != 0 && 10 / x > 1 throws an ArithmeticException.


Practice Q&A

Q: What is the final value of count after this code runs? int count = 0; for (int p = 1; p < n; p++) { for (int q = 1; q <= n; q++) { count++; } } (Assume n is some integer greater than zero.)

A: The outer loop runs n - 1 times (p goes from 1 to n - 1). The inner loop runs n times per outer iteration (q goes from 1 to n). So count = n * (n - 1) = n(n - 1).

Q: Given String str1 = "banana"; String str2 = ""; and the loop initialisation int i = str1.length() - 1; with while (i >= 0) { str2 += str1.substring(i, i + 1); i--; }, what is the value of str2 after the loop?

A: "ananab". The loop starts at the last character and appends each character in reverse order.

Q: Consider int x = 0; for (int j = 1; j < 4; j++) { if (x != 0 && j / x > 0) System.out.print(j / x + " "); else System.out.print(j * x + " "); }. What is printed?

A: 0 0 0 . Since x is 0, the condition x != 0 is false, so short-circuit evaluation skips j / x. The else branch runs every time, printing j * 0 = 0 for each iteration.

Q: What will be printed by the triple-nested loop: int sum = 0; for (int i = 1; i < 2; i++) for (int j = 1; j <= 3; j++) for (int k = 1; k < 4; k++) sum += (i j k); System.out.println(sum);?

A: The outer loop runs once (i = 1). The middle loop runs 3 times (j = 1, 2, 3). The inner loop runs 3 times (k = 1, 2, 3). Sum = 1*(11 + 12 + 13) + 1(21 + 22 + 23) + 1(31 + 32 + 3*3) = 6 + 12 + 18 = 36.

Q: In the pattern-printing code that uses System.out.print(space) and System.out.println(symbol) with num = 5, and a final row of num symbols, which pattern is produced?

A: The first section prints 5 stars on one line. The second section prints a right-aligned triangle (decreasing spaces, one star per line). The third section prints 5 stars again. The result is a right-aligned diamond-like pattern: ***** on top, then stars indented to form a decreasing triangle, then ***** on the bottom. The answer is option (B).


Connections to Other Topics

Iteration connects directly to arrays (Unit 6) and ArrayLists (Unit 7), where you will use for and for-each loops to traverse, search, and modify collections. Nested loops are essential for 2D arrays (Unit 8). Recursion (Unit 10) can often replace iteration, and understanding loops helps you see why recursive calls build up on the call stack in a similar pattern.


Related Terms / Search Tags

for loop, while loop, do-while, enhanced for loop, for-each loop, nested loop, loop tracing, iteration count, accumulator, counter, off-by-one, string traversal, pattern printing, short-circuit evaluation, AP CS A Unit 4, loop variable scope, infinite loop