Iteration in Java (AP CSA Unit 2): Building and Tracing Repeating Processes

While Loops

A while loop is a control structure that repeats a block of code as long as a boolean condition remains true. In Java, it’s called a pre-test loop because the condition is checked before each repetition (including the very first time). If the condition is false at the start, the loop body runs zero times.

What a while loop is (and why it matters)

In programming, many tasks aren’t naturally “do this exactly 10 times.” Instead, they are “keep doing this until something happens”—until the user enters a valid value, until you reach the end of a string, until a running total passes a threshold, or until a search finds a match. A while loop matches this kind of logic because it repeats based on a condition rather than a fixed count.

On the AP Computer Science A exam, while loops matter because you’re expected to:

  • Read and reason about loop behavior (often by tracing variables across iterations).
  • Write correct loops that terminate and correctly update state.
  • Use loops to process Strings and perform repeated calculations.

How a while loop works (mechanics)

The Java syntax is:

while (condition) {
    // loop body
}

Execution follows this pattern:

  1. Evaluate condition.
  2. If it is true, run the loop body.
  3. After the body finishes, go back to step 1.
  4. If condition is false, skip the body and continue after the loop.

The key idea is that something inside the loop must eventually make the condition false (or you must otherwise stop the program). Otherwise you get an infinite loop.

A useful way to think about a loop is in terms of three responsibilities:

  • Initialization: set up variables before the loop starts.
  • Condition: decide whether to keep going.
  • Update: change variables so progress is made toward termination.

If any of these are missing or incorrect, loops tend to misbehave.

Common while loop patterns

1) Counter-controlled repetition (while version)

Even though for loops are common for counting, you can count with a while loop by managing the counter yourself.

Conceptually: “Start at 1; while you haven’t reached 5, keep printing and move to the next number.”

int i = 1;              // initialization
while (i <= 5) {         // condition
    System.out.println(i);
    i++;                 // update
}

If you forget i++, i never changes, and the condition i <= 5 stays true forever.

2) Sentinel-controlled repetition

A sentinel value is a special value that signals “stop.” This is common when you don’t know in advance how many inputs or items you’ll process.

Example: sum numbers until a 0 appears (0 is the sentinel).

int sum = 0;
int value = 5; // imagine this came from input

while (value != 0) {
    sum += value;
    // get next value (simulated here)
    value--;
}

System.out.println("sum = " + sum);

On the exam, the “get next value” step might be another method call, or pulling a character from a String by index, or generating a random number, etc. The loop’s correctness depends on updating the thing you’re testing.

3) Input validation (repeat until valid)

Many programs need to reject invalid data and keep asking until valid. The loop condition often reads like “while input is invalid, ask again.”

Even without actual user input on the AP exam, you’ll see this structure with a variable being repeatedly changed until it’s acceptable.

Tracing a while loop (what the exam often tests)

A big AP skill is being able to trace changes across iterations—especially when a loop variable changes by more than 1, or when multiple variables change.

Consider:

int x = 10;
int y = 0;
while (x > 0) {
    y += x;
    x -= 3;
}
System.out.println(y);

To reason correctly, you track x and y:

  • Start: x = 10, y = 0
  • Iteration 1 (x>0): y = 10, x = 7
  • Iteration 2: y = 17, x = 4
  • Iteration 3: y = 21, x = 1
  • Iteration 4: y = 22, x = -2
  • Stop (x>0 is false). Output is 22.

Common pitfall: students stop one iteration too early because they mentally treat x -= 3 as if it happens before y += x. Inside the loop body, order matters.

While loops with Strings (a very common AP context)

Strings are heavily used early in AP CSA, and loops are a natural way to process them character by character.

Important String tools you’ll typically combine with loops:

  • str.length() gives the number of characters.
  • str.substring(a, b) returns characters from index a up to (not including) b.
  • str.substring(i, i + 1) is a common way to get the single-character String at index i.

Example: count how many times the letter 'a' appears.

public static int countA(String str) {
    int count = 0;
    int i = 0;

    while (i < str.length()) {
        String ch = str.substring(i, i + 1);
        if (ch.equals("a")) {
            count++;
        }
        i++;
    }
    return count;
}

Why i < str.length() and not i <= str.length()? Because the last valid index is str.length() - 1. If i == str.length(), then substring(i, i + 1) would try to go past the end and cause an exception.

What goes wrong in while loops (and how to prevent it)

  • Infinite loops: the condition never becomes false (often because the update is missing, or updates the wrong variable).
  • Off-by-one errors: using <= instead of < (or vice versa) when indexing.
  • Wrong variable in the condition: checking one variable but updating another.
  • Re-initializing inside the loop: resetting a counter each iteration prevents progress.

A practical habit: when you write a while loop, explicitly identify the variable(s) that control termination and point to the line(s) that change them.

Exam Focus
  • Typical question patterns:
    • Trace a while loop and determine the final value printed or returned.
    • Complete a code segment by choosing the correct loop condition or update.
    • Process a String with a loop to count/accumulate/filter characters.
  • Common mistakes:
    • Using i <= str.length() when indexing, causing out-of-bounds substring calls.
    • Forgetting to update the loop control variable (or updating it in the wrong direction).
    • Assuming the loop runs at least once (it might run zero times if the condition starts false).

For Loops

A for loop is a loop structure that packages the three loop responsibilities—initialization, condition, and update—into one compact header. For loops are ideal when you know (or can describe) how a variable changes each time, especially for counting and for stepping through indices.

What a for loop is (and why it matters)

In AP CSA, for loops show up constantly because many problems involve:

  • Repeating an action a specific number of times.
  • Traversing a sequence by index (most commonly a String, and later arrays/ArrayLists).
  • Using mathematical patterns (sum 1..n, count multiples, find maximum, etc.).

A major advantage of the for loop is readability: a reader can quickly see where the loop starts, when it ends, and how it progresses.

How a for loop works (mechanics)

Java syntax:

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

Execution order:

  1. Run initialization once.
  2. Check condition. If false, the loop ends immediately.
  3. Run the body.
  4. Run update.
  5. Go back to step 2.

A key detail: the update happens after the loop body each iteration.

Connecting for loops to while loops

Every for loop can be rewritten as a while loop. For example:

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

is equivalent to:

int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

This equivalence helps when you’re trying to understand a tricky for loop—mentally expand it into initialization, condition, and update.

Typical for loop uses

1) Count-controlled repetition

If you need to repeat something exactly n times, the loop counter often starts at 0 and goes while < n.

int n = 4;
for (int i = 0; i < n; i++) {
    System.out.println("Hello");
}

This prints Hello exactly 4 times.

Why start at 0? In Java, indexing starts at 0, so this pattern matches how you traverse Strings/arrays later.

2) Accumulation (sums and counts)

Many AP problems involve building a total.

Example: compute the sum of integers from 1 to n.

public static int sumToN(int n) {
    int sum = 0;
    for (int i = 1; i <= n; i++) {
        sum += i;
    }
    return sum;
}

Notice how the boundaries match the problem statement: because you want to include n, you use i <= n.

3) Traversing a String by index

A very AP-relevant pattern is scanning a String and applying logic per character.

Example: count vowels.

public static int countVowels(String s) {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        String ch = s.substring(i, i + 1);
        if (ch.equals("a") || ch.equals("e") || ch.equals("i") || ch.equals("o") || ch.equals("u")) {
            count++;
        }
    }
    return count;
}

Common mistake: using s.substring(i, i) (which is always the empty string) instead of i, i + 1.

Scope and loop variable behavior

When you write:

for (int i = 0; i < 10; i++) {
    // ...
}

the variable i is declared inside the for header, and its scope is the loop body (and the header). That means you can’t use i after the loop ends. This is usually helpful because it prevents accidental misuse.

You can also declare the loop variable before the loop if you need it afterward:

int i;
for (i = 0; i < 10; i++) {
    // ...
}
System.out.println("Final i: " + i);

Off-by-one boundaries (the #1 for-loop issue)

A lot of loop errors are really boundary errors:

  • i < n repeats n times if i starts at 0.
  • i <= n repeats n + 1 times if i starts at 0.

When traversing a String of length L, the valid indices are 0 through L - 1. That’s why the standard traversal condition is i < s.length().

Worked example: predicting output

int total = 0;
for (int i = 2; i <= 10; i += 2) {
    total += i;
}
System.out.println(total);

This adds even numbers from 2 to 10 inclusive: 2 + 4 + 6 + 8 + 10 = 30, so it prints 30.

A typical mistake here is to assume the loop ends at 8 because the update is +2, but since the condition is i <= 10, i = 10 is included.

What goes wrong in for loops (and how to prevent it)

  • Changing the loop control variable inside the body: If you also modify i in the body, you can skip values or create infinite loops.
  • Wrong comparison operator: <= vs < is often the difference between correct and out-of-bounds.
  • Update in the wrong direction: If i is decreasing, the condition must match (for example, i >= 0).

A helpful mental check: “Does my update move me closer to making the condition false?” If not, the loop may never stop.

Exam Focus
  • Typical question patterns:
    • Determine the number of loop iterations or final output for a given for loop.
    • Write or choose a for loop header that correctly traverses a String.
    • Identify off-by-one issues in bounds like i <= length.
  • Common mistakes:
    • Using i <= s.length() when accessing index i.
    • Accidentally iterating one too few times (for example, starting at 1 but using < n).
    • Modifying the counter in both the update section and inside the body.

Nested Iteration

Nested iteration means putting one loop inside another loop. The inner loop completes all of its iterations for each single iteration of the outer loop. Nested loops are essential for working with grids, comparing pairs, building tables, and generating combinations.

What nested iteration is (and why it matters)

Some tasks naturally have “layers” of repetition:

  • For each row, process each column.
  • For each character, compare it to every other character.
  • For each test case, run a repeated simulation.

AP CSA uses nested loops to test whether you can reason carefully about:

  • How many times code runs.
  • How variables (especially indices) change.
  • Whether the inner loop resets correctly each time.

Even when the exam isn’t explicitly about “time complexity,” nested loops often lead to lots of iterations, and that affects correctness and tracing.

How nested loops work (mechanics)

A typical structure looks like:

for (int outer = 0; outer < OUTER_LIMIT; outer++) {
    for (int inner = 0; inner < INNER_LIMIT; inner++) {
        // work that depends on outer and inner
    }
}

The critical idea: every time outer increments, inner starts over from its initialization.

If OUTER_LIMIT is 3 and INNER_LIMIT is 4, the body runs 3 * 4 = 12 times.

Nested loops with counting and tables

Example: multiplication table values

This code prints products for a small table:

for (int row = 1; row <= 3; row++) {
    for (int col = 1; col <= 4; col++) {
        System.out.print((row * col) + " ");
    }
    System.out.println();
}

Expected output:

1 2 3 4 
2 4 6 8 
3 6 9 12 

What to notice:

  • The inner loop (col) runs to completion (1 through 4) before row changes.
  • System.out.println() after the inner loop ends creates the line breaks between rows.

A common error is accidentally putting the line break inside the inner loop, which would print each product on its own line and destroy the “row” structure.

Nested loops for comparing pairs (combinations)

Nested loops are also used to compare every pair of items—often with a pattern that avoids duplicate comparisons.

Example: count the number of pairs (i, j) with i < j in a String where the two characters are equal.

public static int countMatchingPairs(String s) {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        for (int j = i + 1; j < s.length(); j++) {
            String a = s.substring(i, i + 1);
            String b = s.substring(j, j + 1);
            if (a.equals(b)) {
                count++;
            }
        }
    }
    return count;
}

Why start j at i + 1?

  • It guarantees i < j.
  • It prevents comparing a character with itself.
  • It avoids counting the same pair twice (so you don’t count both (i, j) and (j, i)).

This “start inner loop based on outer loop” pattern is extremely common in nested-iteration problems.

Nested loops with while loops

You can nest while loops too. The same rule applies: the inner loop must make progress toward its own termination, and it must typically be re-initialized appropriately for each outer iteration.

Example: print a right triangle of * with height 4:

int row = 1;
while (row <= 4) {
    int stars = 1;              // re-initialize for each row
    while (stars <= row) {
        System.out.print("*");
        stars++;
    }
    System.out.println();
    row++;
}

Output:

*
**
***
****

If you mistakenly place int stars = 1; outside the outer loop, then stars won’t reset each row, and the inner loop may run only the first time (or behave unexpectedly).

Tracing nested iteration (how to stay organized)

When tracing nested loops, focus on this repeating cycle:

  • Outer loop chooses a new outer value.
  • Inner loop runs through all inner values.
  • Only then does the outer loop move again.

A practical tracing technique is to write ordered pairs (outer, inner) in the order they occur.

For:

for (int i = 0; i < 2; i++) {
    for (int j = 0; j < 3; j++) {
        System.out.print("(" + i + "," + j + ") ");
    }
}

The order is:

  • (0,0) (0,1) (0,2) (1,0) (1,1) (1,2)

This kind of ordering is exactly what you need for “what is printed” questions.

What goes wrong in nested loops (and how to prevent it)

  • Forgetting to reset the inner loop variable: The inner loop must typically start from its initial value each time the outer loop repeats.
  • Mixing up row/col (or i/j): Using the wrong variable in the condition or update can cause incorrect iteration counts.
  • Off-by-one errors multiply: A single boundary mistake in a nested loop can cause many incorrect outputs or an out-of-bounds error.
  • Printing in the wrong place: In pattern/table problems, whether you print inside the inner loop vs after it changes the entire format.

A helpful naming habit: use meaningful names like row/col instead of only i/j when the loop represents a grid or table.

Exam Focus
  • Typical question patterns:
    • Determine what a nested loop prints (often tables or patterns) and in what order.
    • Count how many times a statement executes given loop bounds.
    • Fill in missing bounds (like starting j at i + 1) to avoid duplicates or meet a condition.
  • Common mistakes:
    • Not re-initializing the inner loop counter for each outer loop iteration.
    • Confusing which loop controls rows vs columns, leading to swapped or malformed output.
    • Off-by-one bounds that lead to substring/index errors when nested loops process Strings.