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 i | Inner j values | Operations |
|---|---|---|
| i = 0 | j = 0, 1, 2, 3 | 4 operations |
| i = 1 | j = 0, 1, 2, 3 | 4 operations |
| i = 2 | j = 0, 1, 2, 3 | 4 operations |
| Total | 12 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 ✍️
-
In a nested loop where the outer runs 5 times and the inner runs 4 times, the inner body executes _______ times total.
-
To get character at index i of a String in the AP subset, use s.substring(i, i + _______).
-
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 ofi < 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.
| Step | i | j | j <= 2? | What happens |
|---|---|---|---|---|
| 1 | 1 | 1 | true | prints 1 1 |
| 2 | 1 | 2 | true | prints 1 2 |
| 3 | 1 | 3 | false | inner loop ends; i++ makes i 2 |
| 4 | 2 | 1 | true | prints 2 1 (j started over at 1) |
| 5 | 2 | 2 | true | prints 2 2 |
| 6 | 2 | 3 | false | inner loop ends; i becomes 3 |
| 7 | 3 | 1 | true | prints 3 1 |
| 8 | 3 | 2 | true | prints 3 2 |
| 9 | 3 | 3 | false | inner 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 = 1executes 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 header | Row for i = 1 | i = 2 | i = 3 | i = 4 | Shape |
|---|---|---|---|---|---|
int j = 1; j <= i; j++ | 1 | 12 | 123 | 1234 | grows |
int j = 1; j < i; j++ | (blank line) | 1 | 12 | 123 | grows, first row empty |
int j = i; j <= 4; j++ | 1234 | 234 | 34 | 4 | shrinks from the left |
int j = i; j >= 1; j-- | 1 | 21 | 321 | 4321 | grows, counting down |
int j = 1; j <= 4 - i; j++ | 123 | 12 | 1 | (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
- For one value of i, write the first j and the last j that pass the test.
- 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
printlnstill ends the line. - 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
| Placement | Where | How many times println runs | Output |
|---|---|---|---|
| A | inside the inner loop | 3 x 3 = 9 | every digit on its own line (9 lines) |
| B | after the inner loop, inside the outer loop | 3 | 123 on three lines |
| C | after the outer loop | 1 | 123123123 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.
| i | j values | i * j | Row printed |
|---|---|---|---|
| 3 | 1, 2, 3 | 3, 6, 9 | 3 6 9 |
| 2 | 1, 2 | 2, 4 | 2 4 |
| 1 | 1 | 1 | 1 |
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.
| Pattern | Outer loop chooses | Inner loop chooses |
|---|---|---|
| Counting pairs | the first value | the second value |
| Building a table | the row | the column |
| Primes in a range | the number to test | each possible divisor |
| Letter pairs in Strings | a position in one word | a 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 header | Pairs visited when both values run from 1 to 4 | How many | Use it when |
|---|---|---|---|
int b = 1; b <= 4; b++ | every (a, b): both (1, 3) and (3, 1), and (2, 2) | 16 | order matters |
int b = a; b <= 4; b++ | only pairs with a <= b, including (2, 2) | 10 | order does not matter, and a value may pair with itself |
int b = a + 1; b <= 4; b++ | only pairs with a < b | 6 | order does not matter, and the two items must differ |
🔑 Key Concept: Starting the inner loop at
a + 1visits 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 print1 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 * cis 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 + " ");
}
}
| n | d values tried | Divisors found | Printed? |
|---|---|---|---|
| 2 | none (2 < 2 is false) | none | yes |
| 3 | 2 | none | yes |
| 4 | 2, 3 | 2 | no |
| 5 | 2, 3, 4 | none | yes |
| 6 | 2 to 5 | 2 and 3 | no |
| 7 | 2 to 6 | none | yes |
| 8 | 2 to 7 | 2 and 4 | no |
| 9 | 2 to 8 | 3 | no |
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);
}
| start | Values that pass value <= 20 | steps printed |
|---|---|---|
| 1 | 1, 2, 4, 8, 16 | 5 |
| 2 | 2, 4, 8, 16 | 4 |
| 3 | 3, 6, 12 | 3 |
| 4 | 4, 8, 16 | 3 |
| 5 | 5, 10, 20 | 3 |
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 ✍️
-
If the primes code runs n from 2 to 30 instead of 2 to 20, how many numbers does it print? _______
-
In the doubling code, how many steps would be printed for start = 6? _______
-
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.
| Call | Matching pairs | Returns |
|---|---|---|
countMatches("cat", "act") | c-c, a-a, t-t | 3 |
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") | none | 0 |
🎯 AP Connection: In free-response code, pull single letters out with
substring(k, k + 1)and compare them withequals. 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.
| Header | Values when the body runs | Body executions |
|---|---|---|
for (int i = 0; i < 10; i++) | 0, 1, ..., 9 | 10 |
for (int i = 1; i <= 10; i++) | 1, 2, ..., 10 | 10 |
for (int i = 5; i < 12; i++) | 5, 6, ..., 11 | 12 - 5 = 7 |
for (int i = 5; i <= 12; i++) | 5, 6, ..., 12 | 12 - 5 + 1 = 8 |
for (int i = 0; i < 10; i += 3) | 0, 3, 6, 9 | 4 |
for (int i = 20; i > 0; i -= 5) | 20, 15, 10, 5 | 4 |
for (int i = 0; i < n; i++) | 0, 1, ..., n - 1 | n |
for (int i = 1; i <= n; i++) | 1, 2, ..., n | n |
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 loop | Executions | Example: for (int i = 0; i < 3; i++) { sum += i; } |
|---|---|---|
initialization int i = 0 | 1 | 1 |
condition i < 3 | k + 1 | 4 (true for 0, 1, 2; false for 3) |
body sum += i | k | 3 |
update i++ | k | 3 |
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
}
}
| Statement | Executions | Reason |
|---|---|---|
int i = 0 | 1 | runs once |
i < 5 | 6 | 5 true + 1 false |
int j = 0 | 5 | once per outer pass |
j < 3 | 5 x 4 = 20 | 4 checks per outer pass |
S: sum += i * j | 5 x 3 = 15 | 3 passes per outer pass |
j++ | 15 | once per S |
i++ | 5 | once 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, 4 | Total for n = 5 | Total for any n |
|---|---|---|---|
int j = 0; j < i; j++ | 0, 1, 2, 3, 4 | 10 | 0 + 1 + ... + (n - 1) = n(n - 1) / 2 |
int j = 0; j <= i; j++ | 1, 2, 3, 4, 5 | 15 | 1 + 2 + ... + n = n(n + 1) / 2 |
int j = i; j < n; j++ | 5, 4, 3, 2, 1 | 15 | n + (n - 1) + ... + 1 = n(n + 1) / 2 |
int j = i + 1; j < n; j++ | 4, 3, 2, 1, 0 | 10 | (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++;
}
}
| n | count (both versions) | Version A: if checked | Version B: if checked |
|---|---|---|---|
| 10 | 4 | 10 * 10 = 100 | 10 |
| 20 | 9 | 400 | 20 |
| 100 | 49 | 10,000 | 100 |
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:
| w | Result | Version 1 | Version 2 |
|---|---|---|---|
"aab" | true | 1 | 3 |
"abcdea" | true | 5 | 15 |
"abcdef" | false | 15 | 15 |
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.
| Bug | Symptom |
|---|---|
| counter or accumulator declared before the outer loop | only the first row is right, or rows pile up |
| inner header updates the outer variable | infinite loop |
| inner header redeclares the outer variable | compile-time error |
| println inside the inner loop | one value per line |
< instead of <= in a dependent bound | rows 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
| Step | Do this |
|---|---|
| 1 | Write the outer variable's values first. Check the first and last value against the header. |
| 2 | For each outer value, write the inner variable's first and last value. Watch for bounds that use the outer variable. |
| 3 | Decide where each statement sits: inner body, outer body, or after both loops. |
| 4 | For a count, add the inner passes row by row, or multiply when every row is the same length. |
| 5 | Look 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.
| Call | Pairs found | Returns |
|---|---|---|
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 + 1to 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
| Point | Earned by |
|---|---|
| Outer loop | visits every a from low to high with no value skipped or added |
| Inner loop | starts at a + 1 (or otherwise guarantees a < b) and includes high |
| Test | compares a + b with target using == |
| Result | initializes 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.
| Call | Returns |
|---|---|
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 < nleaves it off after the last group. Without the if,staircase(3)would return"1/22/333/". - Count the work.
result += rowexecutes 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 ✍️
-
How many characters long is the String returned by
staircase(4)? _______ -
How many times does
result += rowexecute forstaircase(6)? _______ -
For
countPairsSum(1, 10, 10), how many times isa + b == targetevaluated? _______
Common FRQ Deductions on Nested Loops
| Mistake | Why it costs points |
|---|---|
| Inner loop starts at the wrong value | pairs are missed, double-counted, or matched with themselves |
| Accumulator or counter declared in the wrong loop | it resets too often or never resets |
| Bound off by one | a value is skipped, or substring runs past the end of the String |
| Return inside the loops on every path | the method stops after one check |
| Printing the answer instead of returning it | the 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
| Idea | Key fact | Typical trap |
|---|---|---|
| Restart rule (Part 2) | the inner loop re-initializes and runs to completion on every outer pass | thinking 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 in | a println inside the inner loop |
| Pairs (Part 3) | start the inner loop at a + 1 for unordered pairs of different values | starting at a or 1 double-counts or self-pairs |
| Tables and primes (Part 3) | reset the row String or divisor count inside the outer loop | declaring it above the outer loop |
| Letter pairs (Part 3) | compare substring(i, i + 1) with substring(j, j + 1) using equals | using == on Strings |
| Single-loop counts (Part 4) | list the values; condition checks = passes + 1 | counting <= as < |
| Nested counts (Part 4) | constant bounds multiply; dependent bounds add row by row | multiplying when the rows differ |
| Comparing segments (Part 5) | same result, different counts; an early return can save work | assuming 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.
| i | Letter | j values | Comparisons | Matches |
|---|---|---|---|---|
| 0 | s | 1 to 5 | 5 | j = 3 ("s") |
| 1 | e | 2 to 5 | 4 | j = 2 ("e") |
| 2 | e | 3 to 5 | 3 | none |
| 3 | s | 4, 5 | 2 | none |
| 4 | a | 5 | 1 | none |
| 5 | w | none | 0 | none |
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 shape | Inner statement executes |
|---|---|
| outer n passes, inner m passes (constant) | n * m |
| both loops 0 to n - 1, independent | n * n |
inner j < i, outer i = 0 to n - 1 | 0 + 1 + ... + (n - 1) = n(n - 1) / 2 |
inner j <= i or j = i; j < n | n(n + 1) / 2 |
inner j = i + 1; j < n (each pair once) | n(n - 1) / 2 |
| doubling or halving loop | list the values until the test fails |
| any loop condition | checked once more than the body runs |
Error Catalogue
| Symptom | Likely cause | Fix |
|---|---|---|
| later rows blank or rows pile up | counter or accumulator declared above the outer loop | declare it inside the outer loop |
| program never stops | inner header updates the wrong variable | update the inner variable |
| does not compile | inner header redeclares the outer variable | use a new name such as j |
| every value on its own line | println inside the inner loop | move it after the inner loop |
| a pair counted twice or matched with itself | inner loop starts at 0 or at i | start at i + 1 |
| StringIndexOutOfBoundsException | a substring index reaches past the end | keep 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 🎯