while Loops, for Loops, and Counting Iterations

AP Computer Science A · Unit 2 — Selection and Iteration

while

A while loop tests its condition before each pass. If the condition is false at the start, the body never runs at all. Three things must be present or the loop is wrong: an initialisation before the loop, a condition that can become false, and an update inside the body that moves the loop variable toward that condition. Removing the update, or updating a different variable from the one being tested, produces an infinite loop.

for

The header for (init; condition; update) gathers those three parts on one line. Execution order is: run init once, test the condition, run the body, run the update, test again. The loop variable declared in the header exists only inside the loop.

Counting the passes

For for (int i = a; i < b; i++) the body runs b - a times, provided b >= a. Changing < to <= adds exactly one pass. With a step of k, the count is the number of values of i in the range, which is not (b - a) / k in general. When the loop variable indexes a string, the safe upper bound is i < s.length(), because valid indexes run from 0 through s.length() - 1.

HELLO?012345i < s.length() gives exactly 5 passes: 0,1,2,3,4i <= s.length() adds exactly ONE pass — the pass i = 5 goes out of bounds.s.length() is 5, but the last usable index is 4.substring(5, 6) ném StringIndexOutOfBoundsException.
The dashed box is the entire off-by-one error. The string "HELLO" has a length() of 5 but its usable indexes go only up to 4 — the length and the last index differ by exactly one. Changing < to <= in the condition adds one more pass to the loop, and that pass lands in the dashed box. Notably, this error does not always blow up: if the loop body has a return statement that runs before the last pass, the program exits quietly, so the bug stays hidden until it meets data that does not trigger the return.

Worked example: counting passes with a negative step

Count how many times the loop body runs, then give the value printed.

int total = 0;
int passes = 0;
for (int k = 10; k > 0; k -= 3) {
    total += k;
    passes++;
}
System.out.println(passes + " " + total);

Solution

Build a table instead of working it out in your head. Because the step is negative, list the value of k at the start of each pass:

passk at start of passtotal after pass
11010
2717
3421
4122

After the fourth pass, k becomes -2; the condition k > 0 is false, so the loop stops. It prints 4 22.

Why not divide. The formula (10 − 0) / 3 gives 3 and is wrong. With a step other than 1, the number of passes is the number of values that fall in the range, which you must count, not divide — this is exactly where the AP exam sets the most traps.

Common mistake

The costliest error: using i <= s.length() when traversing a string. It runs exactly one extra pass and throws StringIndexOutOfBoundsException — but only with data that makes the loop run to the end, so a sloppy test still comes up green. How to prevent it: for every loop that traverses a string, write down the largest value the loop variable takes, then compare it with s.length() - 1. If it is larger, the loop is broken.

Key takeaway

while checks first and may run zero passes. for (i = a; i < b; i++) runs exactly b − a passes; switching to <= adds one pass. When the step is not 1, count, don't divide.

← Conditional Statements and Nested if · All AP Computer Science A lessons · Practice AP Computer Science A questions (free, instant scoring) · Nested Loops and String Traversal →