Skip to content
🎯⭐ INTERACTIVE LESSON

Loops & Iteration

Learn step-by-step with interactive practice!

Loops & Iteration - Complete Interactive Lesson

Part 1: Core Concepts

🔄 Loops (Advanced)

Part 1 of 7 — Nested Loops, Loop Analysis, and String Processing


Nested Loops

// Print a 3x4 grid of stars
for (int row = 0; row < 3; row++) {
    for (int col = 0; col < 4; col++) {
        System.out.print("* ");
    }
    System.out.println();  // New line after each row
}

Output:

* * * *
* * * *
* * * *

🔑 Nested loop execution count: If the outer loop runs M times and the inner loop runs N times per outer iteration, the inner body runs M x N times total.


Loop Analysis Table

Outer iInner j valuesOperations
i = 0j = 0, 1, 2, 34 operations
i = 1j = 0, 1, 2, 34 operations
i = 2j = 0, 1, 2, 34 operations
Total12 operations

Concept Check 🎯

String Processing with Loops

Reversing a String

String original = "hello";
String reversed = "";
for (int i = original.length() - 1; i >= 0; i--) {
    reversed += original.substring(i, i + 1);
}
// reversed = "olleh"

Checking for a Palindrome

public boolean isPalindrome(String s) {
    for (int i = 0; i < s.length() / 2; i++) {
        String left = s.substring(i, i + 1);
        String right = s.substring(s.length() - 1 - i, s.length() - i);
        if (!left.equals(right)) {
            return false;
        }
    }
    return true;
}

Counting Characters

public int countChar(String s, String target) {
    int count = 0;
    for (int i = 0; i < s.length(); i++) {
        if (s.substring(i, i + 1).equals(target)) {
            count++;
        }
    }
    return count;
}

Sentinel-Controlled Loops

Assume a method getNextScore() returns the next score in a list, and returns -1 once there are no scores left.

int sum = 0;
int value = getNextScore();
while (value != -1) {    // -1 is the sentinel value
    sum += value;
    value = getNextScore();
}

The first value is read before the loop, and the next value is read at the end of the body, so the sentinel itself is never added to sum.

Applied Recall ✍️

  1. In a nested loop where the outer runs 5 times and the inner runs 4 times, the inner body executes _______ times total.

  2. To get character at index i of a String in the AP subset, use s.substring(i, i + _______).

  3. A special value that signals the end of input in a while loop is called a _______ value.

Analyze the Loop 🔍

AP Exam Strategy: Advanced Loops

  • Trace nested loops systematically — write a table of outer and inner variable values
  • Know that inner loop count = outer iterations x inner iterations
  • String processing: always use substring(i, i+1) to get a single character in the AP subset
  • Common error: using i <= s.length() instead of i < s.length() (StringIndexOutOfBoundsException)
  • Palindrome and reversal are classic FRQ patterns — practice these
  • If the inner loop bound depends on the outer variable, the total count is a triangular series

AP-Style Application 🎯

Part 2: Nested Loops: How the Inner Loop Restarts

🔄 Loops (Advanced)

Part 2 of 7 — Nested Loops: How the Inner Loop Restarts


A nested loop is a loop whose body contains another loop (CED Topic 2.11). Part 1 showed the star grid and the rule that an outer loop of M passes around an inner loop of N passes runs the inner body M x N times. This part slows down and traces what happens on every pass, because nearly every nested-loop question on the exam turns on one fact:

🔑 Key Concept: Each time the outer loop body runs, the inner loop starts over from its initialization and runs to completion before the outer loop moves on.

In this part
The restart rule, traced with an (i, j) table
Inner bounds that depend on the outer variable
Where the println goes
Worked example: a countdown times table

The Restart Rule

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 2; j++) {
        System.out.println(i + " " + j);
    }
}

Trace it one condition check at a time. Each row is one evaluation of the inner condition j <= 2.

Stepijj <= 2?What happens
111trueprints 1 1
212trueprints 1 2
313falseinner loop ends; i++ makes i 2
421trueprints 2 1 (j started over at 1)
522trueprints 2 2
623falseinner loop ends; i becomes 3
731trueprints 3 1
832trueprints 3 2
933falseinner loop ends; i becomes 4, i <= 3 is false, outer loop ends

What the Table Shows

  • j changes fastest. i changes only after the inner loop has finished, the way the minute hand goes all the way around before the hour hand moves.
  • The inner initialization runs once per outer pass. int j = 1 executes 3 times here, and each time j is a brand-new variable that starts at 1.
  • The inner condition is checked one more time than the inner body runs, on every outer pass: 3 checks per pass (2 true, 1 false), so 9 checks in all.
  • j does not exist outside the inner loop. A variable declared in a for header is in scope only inside that loop, so using j after the inner loop's closing brace does not compile.

Concept Check 🎯

Segment A

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

When the Inner Bound Depends on the Outer Variable

When the inner header mentions i, each outer pass gets a different number of inner passes. Every pattern below uses the same frame and changes only the inner header.

for (int i = 1; i <= 4; i++) {
    for ( /* inner header */ ) {
        System.out.print(j);
    }
    System.out.println();
}
Inner headerRow for i = 1i = 2i = 3i = 4Shape
int j = 1; j <= i; j++1121231234grows
int j = 1; j < i; j++(blank line)112123grows, first row empty
int j = i; j <= 4; j++1234234344shrinks from the left
int j = i; j >= 1; j--1213214321grows, counting down
int j = 1; j <= 4 - i; j++123121(blank line)shrinks, last row empty

If the frame prints i instead of j, the first header produces 1, 22, 333, 4444: the inner loop decides how many values a row has, and the print statement decides which value appears.

How to Read a Dependent Header Quickly

  1. For one value of i, write the first j and the last j that pass the test.
  2. For a step of 1, the row has last - first + 1 values. If the first value already fails the test, the row is empty but println still ends the line.
  3. Check the first row and the last row before anything else. Together they usually eliminate three answer choices.

🎯 AP Connection: Multiple-choice questions often show four similar triangles and ask which header produces one of them. A < where <= belongs costs one value per row and leaves a blank first or last line, which is exactly the difference between two of the choices.

Match the Header 🔍

Use the frame above (outer loop i = 1 to 4, inner loop prints one value, println after the inner loop).

Where the println Goes

A statement runs as many times as the loop it sits in. The same loops give three different outputs depending on where one System.out.println(); is placed.

for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= 3; j++) {
        System.out.print(j);
        // Placement A: System.out.println(); here
    }
    // Placement B: System.out.println(); here
}
// Placement C: System.out.println(); here
PlacementWhereHow many times println runsOutput
Ainside the inner loop3 x 3 = 9every digit on its own line (9 lines)
Bafter the inner loop, inside the outer loop3123 on three lines
Cafter the outer loop1123123123 on one line

Placement B is the usual "grid" layout: the inner loop builds one row, and the println ends that row before the outer loop starts the next one.

Worked Example: A Countdown Times Table

for (int i = 3; i >= 1; i--) {
    for (int j = 1; j <= i; j++) {
        System.out.print(i * j + " ");
    }
    System.out.println();
}

Step 1 — Outer values. i takes the values 3, 2, 1. Then i becomes 0, and 0 >= 1 is false.

Step 2 — Inner values for each i. The inner loop runs j from 1 up to the current i.

ij valuesi * jRow printed
31, 2, 33, 6, 93 6 9
21, 22, 42 4
1111

Step 3 — Output.

3 6 9
2 4
1

Step 4 — Check the expression. i * j + " " multiplies first, because * has higher precedence than +, and then joins the space. Writing i + j + " " would add instead, and writing "" + i + j would glue the two digits together as text.

AP-Style Application 🎯

int total = 0;
for (int i = 1; i <= 3; i++) {
    for (int j = i; j <= 3; j++) {
        total += j;
    }
}
System.out.println(total);

Part 3: Nested Loop Algorithms: Pairs, Tables, and Primes

🔄 Loops (Advanced)

Part 3 of 7 — Nested Loop Algorithms: Pairs, Tables, and Primes


Part 2 traced how nested loops run. This part puts them to work (CED Topic 2.11). Reach for a nested loop whenever a problem says every combination: every pair of numbers, every row and column of a table, every possible divisor of every number in a range, or every letter of one word against every letter of another.

PatternOuter loop choosesInner loop chooses
Counting pairsthe first valuethe second value
Building a tablethe rowthe column
Primes in a rangethe number to testeach possible divisor
Letter pairs in Stringsa position in one worda position in the other word, or later in the same word

Counting Pairs

How many ways can two six-sided dice show a total of 7? Let a be the first die and b the second.

int count = 0;
for (int a = 1; a <= 6; a++) {
    for (int b = 1; b <= 6; b++) {
        if (a + b == 7) {
            count++;
        }
    }
}
System.out.println(count);

The inner body checks all 6 x 6 = 36 combinations. Six of them add to 7: (1, 6), (2, 5), (3, 4), (4, 3), (5, 2) and (6, 1), so the program prints 6.

Ordered or Unordered?

Here (2, 5) and (5, 2) are different outcomes, because the dice are different. When order does not matter, such as choosing two players from a team, start the inner loop later so each pair is visited once.

Inner headerPairs visited when both values run from 1 to 4How manyUse it when
int b = 1; b <= 4; b++every (a, b): both (1, 3) and (3, 1), and (2, 2)16order matters
int b = a; b <= 4; b++only pairs with a <= b, including (2, 2)10order does not matter, and a value may pair with itself
int b = a + 1; b <= 4; b++only pairs with a < b6order does not matter, and the two items must differ

🔑 Key Concept: Starting the inner loop at a + 1 visits each unordered pair of different values exactly once. With that header, the dice code finds only (1, 6), (2, 5) and (3, 4).

Concept Check 🎯

Use the dice code above.

Building a Table Row by Row

for (int r = 1; r <= 4; r++) {
    String row = "";
    for (int c = 1; c <= 4; c++) {
        row += r * c + " ";
    }
    System.out.println(row);
}

Output:

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

Trace of the pass r = 2: row starts as "", then becomes "2 ", "2 4 ", "2 4 6 " and "2 4 6 8 ", and the println shows it.

  • String row = "" sits inside the outer loop, so every row starts empty. If it were declared above the outer loop, the second line would print 1 2 3 4 2 4 6 8 , because the String would keep everything from the first row.
  • row += r * c + " " evaluates the right side first: r * c is an int product, and + " " turns it into text before it is appended.

Primes in a Range: A Divisor Loop for Every Number

for (int n = 2; n <= 20; n++) {
    int divisors = 0;
    for (int d = 2; d < n; d++) {
        if (n % d == 0) {
            divisors++;
        }
    }
    if (divisors == 0) {
        System.out.print(n + " ");
    }
}
nd values triedDivisors foundPrinted?
2none (2 < 2 is false)noneyes
32noneyes
42, 32no
52, 3, 4noneyes
62 to 52 and 3no
72 to 6noneyes
82 to 72 and 4no
92 to 83no

The whole loop prints 2 3 5 7 11 13 17 19 . Two details matter: int divisors = 0 must be reset inside the outer loop, and for n = 2 the inner loop runs zero times, which is exactly why 2 is correctly reported as prime.

A while Loop Inside a for Loop

The inner loop does not have to be a for loop. Here the inner loop counts how many times a starting value can be doubled before it passes 20.

for (int start = 1; start <= 5; start++) {
    int value = start;
    int steps = 0;
    while (value <= 20) {
        value *= 2;
        steps++;
    }
    System.out.println(start + ": " + steps);
}
startValues that pass value <= 20steps printed
11, 2, 4, 8, 165
22, 4, 8, 164
33, 6, 123
44, 8, 163
55, 10, 203

The number of inner passes is not fixed: it depends on start, and you find it by listing values until the condition fails.

Applied Recall ✍️

  1. If the primes code runs n from 2 to 30 instead of 2 to 20, how many numbers does it print? _______

  2. In the doubling code, how many steps would be printed for start = 6? _______

  3. In the multiplication table code, what is the last number printed? _______

Letter Pairs in Strings

Nested loops can compare letters in pairs. These two algorithms are new; they are not the single-loop traversals from the Strings topic.

Does Any Letter Repeat?

public static boolean hasRepeat(String word) {
    for (int i = 0; i < word.length(); i++) {
        for (int j = i + 1; j < word.length(); j++) {
            String a = word.substring(i, i + 1);
            String b = word.substring(j, j + 1);
            if (a.equals(b)) {
                return true;
            }
        }
    }
    return false;
}
  • The inner loop starts at i + 1, so each pair of positions is checked once and no letter is compared with itself.
  • hasRepeat("abca"): i = 0 compares "a" with "b", then "c", then "a", and returns true after 3 comparisons.
  • hasRepeat("planet") checks all 15 pairs, finds no match, and returns false only after both loops finish.

Count Matching Letter Pairs Between Two Words

public static int countMatches(String first, String second) {
    int count = 0;
    for (int i = 0; i < first.length(); i++) {
        for (int j = 0; j < second.length(); j++) {
            if (first.substring(i, i + 1).equals(second.substring(j, j + 1))) {
                count++;
            }
        }
    }
    return count;
}

Every letter of first is compared with every letter of second, so the inner loop starts at 0 each time.

CallMatching pairsReturns
countMatches("cat", "act")c-c, a-a, t-t3
countMatches("too", "oat")t-t, and each "o" of "too" with the "o" of "oat"3
countMatches("noon", "on")each of the four letters matches one letter of "on"4
countMatches("abc", "xyz")none0

🎯 AP Connection: In free-response code, pull single letters out with substring(k, k + 1) and compare them with equals. The Java Quick Reference methods are enough for every letter-pair task.

Letter Pairs Check 🎯

Part 4: Informal Run-Time Analysis: Counting Statement Executions

🔄 Loops (Advanced)

Part 4 of 7 — Informal Run-Time Analysis: Counting Statement Executions


How much work does a segment of code do? CED Topic 2.12 answers that question with a statement execution count: the number of times a particular statement is executed when the program runs. You find the count informally, by tracing the loop or by reasoning about its header, and the answer is either a number or an expression in a variable such as n.

In this part
Counting the passes of a single loop
Condition checks vs. body executions
Nested loops with constant bounds: multiply
Nested loops with dependent bounds: add up the rows
Loops that double or halve: list the values

🎯 AP Connection: Exam questions phrase this as "How many times is the statement executed?" or "How many times is the string printed?" Count exactly. An answer that is off by one is a wrong answer.

Counting a Single Loop

Method: list the values the loop variable has each time the body runs, then count them. For a step of 1, a shortcut works: an exclusive upper bound gives end - start passes, and an inclusive one gives end - start + 1.

HeaderValues when the body runsBody executions
for (int i = 0; i < 10; i++)0, 1, ..., 910
for (int i = 1; i <= 10; i++)1, 2, ..., 1010
for (int i = 5; i < 12; i++)5, 6, ..., 1112 - 5 = 7
for (int i = 5; i <= 12; i++)5, 6, ..., 1212 - 5 + 1 = 8
for (int i = 0; i < 10; i += 3)0, 3, 6, 94
for (int i = 20; i > 0; i -= 5)20, 15, 10, 54
for (int i = 0; i < n; i++)0, 1, ..., n - 1n
for (int i = 1; i <= n; i++)1, 2, ..., nn

Condition Checks vs. Body Executions

Different parts of a loop run different numbers of times. For a for loop whose body runs k times:

Part of the loopExecutionsExample: for (int i = 0; i < 3; i++) { sum += i; }
initialization int i = 011
condition i < 3k + 14 (true for 0, 1, 2; false for 3)
body sum += ik3
update i++k3

The extra condition check is the one that comes out false and ends the loop. A while loop follows the same rule: its condition is checked once more than its body runs.

Concept Check 🎯

Nested Loops with Constant Bounds: Multiply

int sum = 0;
for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 3; j++) {
        sum += i * j;     // statement S
    }
}
StatementExecutionsReason
int i = 01runs once
i < 565 true + 1 false
int j = 05once per outer pass
j < 35 x 4 = 204 checks per outer pass
S: sum += i * j5 x 3 = 153 passes per outer pass
j++15once per S
i++5once per outer pass

When the outer loop runs n times and the inner loop runs m times on every pass, the inner statement executes n * m times. When both loops run n times, the inner statement executes n * n times. That count grows quickly: n = 10 gives 100 executions, and doubling n to 20 gives 400, four times as many.

Nested Loops with Dependent Bounds: Add Up the Rows

When the inner bound uses i, the inner loop runs a different number of times on each outer pass, so multiplying does not work. Count each outer pass separately and add.

int count = 0;
for (int i = 0; i < n; i++) {
    for (int j = 0; j < i; j++) {
        count++;     // statement S
    }
}

For n = 5, S runs 0 times when i = 0, once when i = 1, and so on: 0 + 1 + 2 + 3 + 4 = 10.

Inner header (outer: i = 0 to n - 1)Passes for i = 0, 1, 2, 3, 4Total for n = 5Total for any n
int j = 0; j < i; j++0, 1, 2, 3, 4100 + 1 + ... + (n - 1) = n(n - 1) / 2
int j = 0; j <= i; j++1, 2, 3, 4, 5151 + 2 + ... + n = n(n + 1) / 2
int j = i; j < n; j++5, 4, 3, 2, 115n + (n - 1) + ... + 1 = n(n + 1) / 2
int j = i + 1; j < n; j++4, 3, 2, 1, 010(n - 1) + ... + 0 = n(n - 1) / 2

The sum shortcut comes from pairing the ends: in 1 + 2 + 3 + 4 + 5, the pairs 1 + 5 and 2 + 4 each make 6, and with the middle 3 the total is 5 x 6 / 2 = 15. You can always fall back on writing the per-pass counts and adding them.

Count the Inner Statement 🔍

Worked Example: Loops That Double or Halve

Some loops do not step by a constant. Count them by listing the values.

int k = 1;
int steps = 0;
while (k < 100) {
    k *= 2;
    steps++;
}

Step 1 — List k at each check. 1, 2, 4, 8, 16, 32, 64, 128.

Step 2 — Mark the checks that pass. The first seven values are less than 100, and 128 fails.

Step 3 — Count. The body runs 7 times and the condition is checked 8 times. A loop that added 1 to k instead of doubling it would need 99 passes to reach 100.

Halving works the same way. With int n = 64; while (n > 1) { n /= 2; }, n takes the values 64, 32, 16, 8, 4, 2 while the test passes, so the body runs 6 times. Starting from 100 also gives 6 passes, because int division drops the remainder: 100, 50, 25, 12, 6, 3, and then n becomes 1.

Inside another loop. A doubling loop nested in an outer loop multiplies like any constant inner loop:

int count = 0;
for (int i = 0; i < 4; i++) {
    for (int k = 1; k < 16; k *= 2) {
        count++;
    }
}

The inner loop runs for k = 1, 2, 4, 8, which is 4 passes, on each of 4 outer passes, so count++ executes 4 * 4 = 16 times.

AP-Style Application 🎯

int count = 0;
for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
        if (j % i == 0) {
            count++;
        }
    }
}

Part 5: Comparing Algorithms and Nested-Loop Pitfalls

🔄 Loops (Advanced)

Part 5 of 7 — Comparing Algorithms and Nested-Loop Pitfalls


Two segments can produce the same result and still do very different amounts of work. CED Topic 2.12 asks you to compare iterative code by its statement execution counts, and CED Topic 2.11 questions often hide a nested-loop bug in one answer choice. This part covers both.

In this part
Same answer, different counts
Stopping early with return
A catalogue of nested-loop bugs

Same Answer, Different Counts

Both segments count the pairs (a, b) of positive integers with a < b and a + b == n.

Version A checks every combination.

int count = 0;
for (int a = 1; a <= n; a++) {
    for (int b = 1; b <= n; b++) {
        if (a < b && a + b == n) {
            count++;
        }
    }
}

Version B computes the partner directly.

int count = 0;
for (int a = 1; a <= n; a++) {
    int b = n - a;
    if (a < b) {
        count++;
    }
}
ncount (both versions)Version A: if checkedVersion B: if checked
10410 * 10 = 10010
20940020
1004910,000100

Version A's if statement executes n * n times; Version B's executes n times. When n doubles, A's count becomes four times as large while B's only doubles. Both produce the correct answer, but for large n Version B does far less work.

A Second Comparison

Segment I

int total = 0;
for (int i = 1; i <= n; i++) {
    total += i;
}

Segment II

int total = 0;
for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= i; j++) {
        total++;
    }
}

Both end with total equal to 1 + 2 + ... + n. Segment I executes total += i n times, and Segment II executes total++ 1 + 2 + ... + n = n(n + 1) / 2 times.

Stopping Early with return

The hasRepeat method from Part 3 returns as soon as it finds a matching pair. Compare it with a version that records the answer in a flag and keeps looking.

// Version 1: returns at the first match
public static boolean hasRepeat(String w) {
    for (int i = 0; i < w.length(); i++) {
        for (int j = i + 1; j < w.length(); j++) {
            if (w.substring(i, i + 1).equals(w.substring(j, j + 1))) {
                return true;
            }
        }
    }
    return false;
}

// Version 2: checks every pair, then answers
public static boolean hasRepeatFlag(String w) {
    boolean found = false;
    for (int i = 0; i < w.length(); i++) {
        for (int j = i + 1; j < w.length(); j++) {
            if (w.substring(i, i + 1).equals(w.substring(j, j + 1))) {
                found = true;
            }
        }
    }
    return found;
}

Number of equals calls:

wResultVersion 1Version 2
"aab"true13
"abcdea"true515
"abcdef"false1515

Version 2 always checks all 6 * 5 / 2 = 15 pairs of a six-letter word. Version 1 saves work only when a match turns up early; when there is no repeat, it checks every pair too.

🔑 Key Concept: An execution count can depend on the input, not just on n. When an exam question asks for a count, check whether a return can end the loops before the bounds do.

Concept Check 🎯

Use Segments I and II and Versions 1 and 2 above.

A Catalogue of Nested-Loop Bugs

1. The inner counter is never reset

int j = 0;
for (int i = 0; i < 3; i++) {
    while (j < 4) {
        System.out.print("*");
        j++;
    }
    System.out.println();
}

The intent is three rows of four stars. The first pass prints ****, but j is still 4 when the second pass begins, so the while loop runs zero times and the last two lines are blank. Declaring int j = 0; inside the outer loop fixes it. The same bug happens with a String accumulator such as row declared above the outer loop: each line then repeats everything printed before it.

2. The wrong variable is updated

for (int i = 0; i < 3; i++) {
    for (int j = 0; j < 4; i++) {   // i++ instead of j++
        System.out.print("*");
    }
}

j never changes, so j < 4 stays true forever: an infinite loop.

3. The outer variable is reused

Writing for (int i = 0; i < 2; i++) inside a loop that already declared int i does not compile, because i is already defined in that scope. If i is declared once above both loops and both headers assign to it, the code compiles, but the inner loop resets i on every pass. With an outer test of i < 5 and an inner test of i < 2, i bounces between 0 and 3 forever.

4. The println is in the wrong loop

Inside the inner loop it ends every value's line; after the outer loop it runs only once (Part 2).

5. Off by one in a dependent bound

With j < i where j <= i was intended, every row is one value short and the first row is empty.

BugSymptom
counter or accumulator declared before the outer looponly the first row is right, or rows pile up
inner header updates the outer variableinfinite loop
inner header redeclares the outer variablecompile-time error
println inside the inner loopone value per line
< instead of <= in a dependent boundrows one short, first row blank

Diagnose the Bug 🔍

AP-Style Application 🎯

The segment is meant to print 1, 12 and 123 on three lines.

String row = "";
for (int i = 1; i <= 3; i++) {
    for (int j = 1; j <= i; j++) {
        row += j;
    }
    System.out.println(row);
}

Part 6: AP-Style Practice

🔄 Loops (Advanced)

Part 6 of 7 — AP-Style Practice


Nested loops appear in AP multiple-choice questions as output traces and as "how many times" counts, and free-response question 1 (Methods and Control Structures) can ask you to write a method with a loop inside a loop. This part practices both, using only the Java Quick Reference subset.

How to Attack a Nested-Loop Question

StepDo this
1Write the outer variable's values first. Check the first and last value against the header.
2For each outer value, write the inner variable's first and last value. Watch for bounds that use the outer variable.
3Decide where each statement sits: inner body, outer body, or after both loops.
4For a count, add the inner passes row by row, or multiply when every row is the same length.
5Look for an early return, a variable that is never reset, or an index that runs past the end of a String.

🔑 Key Concept: Most wrong answers come from one slip: forgetting that the inner loop restarts, counting a < bound as <=, or printing in the wrong loop.

Practice Set 1: Tracing and Counting 🎯

Segment A

int count = 0;
for (int i = 0; i < 4; i++) {
    for (int j = i; j < 4; j++) {
        if ((i + j) % 2 == 0) {
            count++;
        }
    }
}
System.out.println(count);

Segment B

String a = "tent";
String b = "net";
for (int i = 0; i < a.length(); i++) {
    for (int j = 0; j < b.length(); j++) {
        if (a.substring(i, i + 1).equals(b.substring(j, j + 1))) {
            System.out.print(i + "" + j + " ");
        }
    }
}

FRQ-Style Task 1 — countPairsSum

Prompt. Write a static method countPairsSum that returns the number of pairs (a, b) of integers with low <= a < b <= high and a + b == target.

CallPairs foundReturns
countPairsSum(1, 6, 7)(1, 6), (2, 5), (3, 4)3
countPairsSum(1, 10, 10)(1, 9), (2, 8), (3, 7), (4, 6)4
countPairsSum(3, 5, 8)(3, 5)1
countPairsSum(5, 5, 10)none: a < b rules out (5, 5)0

Plan Before You Write

  • The outer loop picks a from low to high, inclusive.
  • The inner loop picks b from a + 1 to high, so every pair has a < b and is counted once.
  • Test the sum, count, and return the count after both loops.

Solution

public static int countPairsSum(int low, int high, int target) {
    int count = 0;
    for (int a = low; a <= high; a++) {
        for (int b = a + 1; b <= high; b++) {
            if (a + b == target) {
                count++;
            }
        }
    }
    return count;
}

What a Rubric Looks For

PointEarned by
Outer loopvisits every a from low to high with no value skipped or added
Inner loopstarts at a + 1 (or otherwise guarantees a < b) and includes high
Testcompares a + b with target using ==
Resultinitializes the count before the loops, increments it, and returns it after both loops

Practice Set 2: Reasoning About countPairsSum 🎯

FRQ-Style Task 2 — staircase

Prompt. Write a static method staircase that returns a String made of n groups separated by "/". Group k is the digit k written k times. If n is 0, return the empty String.

CallReturns
staircase(1)"1"
staircase(3)"1/22/333"
staircase(4)"1/22/333/4444"
staircase(0)""

Solution

public static String staircase(int n) {
    String result = "";
    for (int row = 1; row <= n; row++) {
        for (int k = 1; k <= row; k++) {
            result += row;
        }
        if (row < n) {
            result += "/";
        }
    }
    return result;
}
  • The inner loop builds one group. It appends row exactly row times, so its bound depends on the outer variable.
  • The separator goes in the outer loop, after the inner loop. The test row < n leaves it off after the last group. Without the if, staircase(3) would return "1/22/333/".
  • Count the work. result += row executes 1 + 2 + ... + n times, so 10 times for n = 4.

The Classic Mistake

Putting the separator inside the inner loop, still guarded by row < n, places a "/" after every digit of the early groups: staircase(3) returns "1/2/2/333".

Applied Recall ✍️

  1. How many characters long is the String returned by staircase(4)? _______

  2. How many times does result += row execute for staircase(6)? _______

  3. For countPairsSum(1, 10, 10), how many times is a + b == target evaluated? _______

Common FRQ Deductions on Nested Loops

MistakeWhy it costs points
Inner loop starts at the wrong valuepairs are missed, double-counted, or matched with themselves
Accumulator or counter declared in the wrong loopit resets too often or never resets
Bound off by onea value is skipped, or substring runs past the end of the String
Return inside the loops on every paththe method stops after one check
Printing the answer instead of returning itthe method must return a value to its caller
Comparing Strings with ==compares references, not contents

🎯 AP Connection: Write each loop header from the specification before writing the body: what is the first value, what is the last value, and is the last value included? Most nested-loop FRQ points are won or lost in the headers.

Part 7: Synthesis Review

🔄 Loops (Advanced)

Part 7 of 7 — Synthesis Review


This part ties the topic together: how nested loops run (CED Topic 2.11), the algorithms built from them, and how to count statement executions (CED Topic 2.12). Use the tables as a checklist, then test yourself on mixed questions.

The Topic on One Page

IdeaKey factTypical trap
Restart rule (Part 2)the inner loop re-initializes and runs to completion on every outer passthinking j keeps its value from the last pass
Dependent bounds (Part 2)a header such as j <= i gives rows of different lengths< vs <= leaves a blank first or last row
println placement (Part 2)a statement runs as often as the loop it sits ina println inside the inner loop
Pairs (Part 3)start the inner loop at a + 1 for unordered pairs of different valuesstarting at a or 1 double-counts or self-pairs
Tables and primes (Part 3)reset the row String or divisor count inside the outer loopdeclaring it above the outer loop
Letter pairs (Part 3)compare substring(i, i + 1) with substring(j, j + 1) using equalsusing == on Strings
Single-loop counts (Part 4)list the values; condition checks = passes + 1counting <= as <
Nested counts (Part 4)constant bounds multiply; dependent bounds add row by rowmultiplying when the rows differ
Comparing segments (Part 5)same result, different counts; an early return can save workassuming an early return always helps

Worked Example: Putting It Together

String word = "seesaw";
int pairs = 0;
for (int i = 0; i < word.length(); i++) {
    for (int j = i + 1; j < word.length(); j++) {
        if (word.substring(i, i + 1).equals(word.substring(j, j + 1))) {
            pairs++;
        }
    }
}
int total = word.length() * (word.length() - 1) / 2;
System.out.println(pairs + " of " + total);

Step 1 — Index the word. s(0) e(1) e(2) s(3) a(4) w(5), length 6.

Step 2 — Trace by outer pass.

iLetterj valuesComparisonsMatches
0s1 to 55j = 3 ("s")
1e2 to 54j = 2 ("e")
2e3 to 53none
3s4, 52none
4a51none
5wnone0none

Step 3 — Count. pairs is 2, and the equals call runs 5 + 4 + 3 + 2 + 1 + 0 = 15 times, which matches total = 6 * 5 / 2 = 15.

Step 4 — Output. 2 of 15. The + operators join left to right, and the int division in total is exact because 6 * 5 is even.

Mixed Review 1 🎯

Segment A

for (int i = 1; i <= 3; i++) {
    String line = "";
    for (int j = 3; j >= i; j--) {
        line += j;
    }
    System.out.print(line + " ");
}

Segment B

int c = 0;
for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j += 2) {
        c++;
    }
}

Counting Reference

Loop shapeInner statement executes
outer n passes, inner m passes (constant)n * m
both loops 0 to n - 1, independentn * n
inner j < i, outer i = 0 to n - 10 + 1 + ... + (n - 1) = n(n - 1) / 2
inner j <= i or j = i; j < nn(n + 1) / 2
inner j = i + 1; j < n (each pair once)n(n - 1) / 2
doubling or halving looplist the values until the test fails
any loop conditionchecked once more than the body runs

Error Catalogue

SymptomLikely causeFix
later rows blank or rows pile upcounter or accumulator declared above the outer loopdeclare it inside the outer loop
program never stopsinner header updates the wrong variableupdate the inner variable
does not compileinner header redeclares the outer variableuse a new name such as j
every value on its own lineprintln inside the inner loopmove it after the inner loop
a pair counted twice or matched with itselfinner loop starts at 0 or at istart at i + 1
StringIndexOutOfBoundsExceptiona substring index reaches past the endkeep i < length() when calling substring(i, i + 1)

🎯 AP Connection: When a count question offers both n * n and n(n - 1) / 2, look at where the inner loop starts. Constant bounds give the product; a start that moves with the outer variable gives a sum.

Quick Evaluation 🔍

Mixed Review 2 🎯