Nested Loops and String Traversal

AP Computer Science A · Unit 2 — Selection and Iteration

Nested loops

When a loop appears inside another loop, the inner loop runs to completion on every single pass of the outer loop. If the outer loop makes m passes and the inner loop makes n passes each time, the innermost statement runs m * n times. The count is a product, not a sum.

When the inner bound depends on the outer variable, the total is a sum rather than a product. For for (int i = 0; i < n; i++) for (int j = i; j < n; j++) the inner loop runs n, then n-1, then n-2 passes, so the total is n(n+1)/2.

Traversing a String

Strings are traversed by index. The two methods used constantly are s.length() and s.substring(i, i + 1), which returns the one-character string at index i. Comparison uses .equals(...), never ==.

To examine a pair of neighbouring characters, use s.substring(i, i + 2). The loop bound must then be i < s.length() - 1, because the last starting position for a two-character window is s.length() - 2. Every window of width w shortens the usable range by w - 1.

i \ j01234012345 passes4 passes3 passes2 passes1 pass15 passesThe dark cells are the (i, j) pairs that actually run when the inner loop starts at j = i.Counting the whole 5 x 5 = 25 grid is the mistake of treating the inner bound as independent of i.
This figure replaces memorizing a formula. Each cell is one run of the innermost body; the dark region is the upper triangle because j starts at i rather than at 0. Adding row by row: 5 + 4 + 3 + 2 + 1 = 15, exactly n(n+1)/2 with n = 5. Two errors appear right on the figure: counting all 25 cells forgets that the inner bound depends on the outer loop; counting 10 cells uses j = i + 1 — that is, it drops the diagonal, exactly one cell per row.

Worked example: two-character window

The string word has at least two characters. The code below counts how many times the substring "an" appears. Give the result for word = "banana", then explain why the loop bound is word.length() - 1.

int count = 0;
for (int i = 0; i < word.length() - 1; i++) {
    if (word.substring(i, i + 2).equals("an")) {
        count++;
    }
}

Solution

List each window. The string "banana" has length 6, so i runs from 0 to 4:

i01234
windowbaannaanna

Two windows match "an", at i = 1 and i = 3. The result is count equal to 2.

Why the bound is length() - 1. The window is 2 wide, so the last starting position must be 4, that is length() - 2. The condition i < length() - 1 gives exactly 4 as the largest value. If you write i < word.length(), the pass i = 5 calls substring(5, 7) and throws an exception.

Watch for overlapping windows. This loop also counts overlapping occurrences, because i increases by 1 each pass. To count non-overlapping occurrences you must jump i += 2 on a match — these are two different problems, and the question always states which one it is asking.

Common mistake

The costliest error: keeping the bound i < s.length() when switching from a one-character window to a two-character window. The loop runs correctly until the last pass and only then blows up, so a test with a short string may still pass. How to prevent it: every time you write substring(i, i + w), lower the bound to i < s.length() - w + 1 in the same step — if you have changed the window but not the bound, do not move on to another line.

Key takeaway

Independent nested loops multiply; when the inner bound depends on the outer loop, add up row by row. For a window of width w, the upper bound drops to s.length() - w. Always compare strings with .equals.

← while Loops, for Loops, and Counting Iterations · All AP Computer Science A lessons · Practice AP Computer Science A questions (free, instant scoring) · Anatomy of a Class: Fields, Encapsulation, Constructors →