AP Computer Science A · Study guide

for Loop Processes

AP® Computer Science A · Selection and Iteration

for Loops

The for loop's three-part header, the exact order in which the initialization, Boolean expression, body, and update run, how to count passes, and how every for loop corresponds to an equivalent while loop.

Big Picture

A for loop is a type of iterative statement. There are three parts in a for loop header: the initialization, the Boolean expression, and the update. The initialization runs only once, before the first evaluation of the Boolean expression; the variable it creates is the loop control variable. The Boolean expression is evaluated immediately after the initialization and then after each update, until it is false, and each update runs after the entire loop body. A for loop can be rewritten into an equivalent while loop, and vice versa.

1The for Loop Header

Counting loops are so common that Java gives them a compact form. In for (int i = 1; i <= 5; i++), the header holds the three parts of a counting loop, separated by semicolons. int i = 1 is the initialization, i <= 5 is the Boolean expression, and i++ is the update. The body in braces follows the header, exactly as in a while loop.

The variable created in the initialization is the loop control variable. By convention it is often named i, j, or k when it simply counts, but a descriptive name such as day or row is clearer when the value means something. Gathering the start, stopping test, and step into one line makes a loop's range visible at a glance.

The update is usually written with the increment or decrement operator, i++ or i--, or with a compound assignment such as i += 2. Each of these is a complete statement that changes the loop control variable by a fixed amount. The update does not end with a semicolon, because the closing parenthesis of the header ends it.

Figure 1. There are three parts in a for loop header: the initialization, the Boolean expression, and the update.
Part of the headerExampleWhen it runs
Initializationint i = 1Once, before the first evaluation of the Boolean expression
Boolean expressioni <= 5Immediately after the initialization, then after each update, until false
Updatei++After the entire loop body, before the expression is evaluated again
Worked Example 1 A first for loop

Counting From 1 to 5

Predict the output.

Code
for (int i = 1; i <= 5; i++)
{
    System.out.println("pass " + i);
}
System.out.println("done");
Output
pass 1
pass 2
pass 3
pass 4
pass 5
done
  1. 1Initialization. int i = 1 runs once.
  2. 2Check, body, update. 1 <= 5 is true, the body prints "pass 1", then i++ makes i 2, and the check repeats.
  3. 3The end. After the body prints "pass 5", the update makes i 6, the check 6 <= 5 is false, and the loop ends.
Result: The output is pass 1 through pass 5, then done. The header packs the initialization, the Boolean expression, and the update of a counting loop into one line.
Common Mistake 1 · Using Commas Instead of Semicolons

The three parts of a for header are separated by semicolons: for (int i = 0; i < 5; i++). Writing for (int i = 0, i < 5, i++) does not compile. There is no semicolon after the update.

2The Order of Execution

A for loop runs its parts in a fixed order. In a for loop, the initialization statement is only executed once before the first Boolean expression evaluation. The Boolean expression is evaluated immediately after the loop control variable is initialized and then following each execution of the update, until it is false. In each iteration, the update is executed after the entire loop body is executed and before the Boolean expression is evaluated again.

So the sequence is: initialize; check; body; update; check; body; update; … ; check (false). As with a while loop, the body may run zero times if the first check is false, and there is always one more check than there are passes. Because the update comes after the body, the body sees the loop control variable's value before each update.

Figure 2. The initialization runs once, before the first check. The Boolean expression is evaluated after the initialization and after each update; each update runs after the entire body.
EventiCheckOutput
initialization1
check11 <= 5 true
body1pass 1
update2
check22 <= 5 true
…………
update6
check66 <= 5 falseloop ends
Worked Example 2 Update after the body

Changing the Control Variable Inside the Body

This loop also changes i in its body, which is confusing style but shows exactly when the update runs. Predict the output.

Code
for (int i = 0; i < 10; i++)
{
    System.out.println(i);
    i = i + 2;
}
Output
0
3
6
9
  1. 1Pass 1. Prints 0; the body adds 2 (i = 2); then the update adds 1 (i = 3).
  2. 2Pass 2. Prints 3; i becomes 5, then 6.
  3. 3Passes 3 and 4. Print 6 and 9; after pass 4, i becomes 11, then 12, and 12 < 10 is false.
Result: The output is 0, 3, 6, 9. The update runs after the entire body, so changes made in the body are followed by the header's update. Keep all changes to the loop control variable in the header to avoid surprises.
Common Mistake 2 · Thinking the Update Runs Before the Body

On the first pass, the body sees the initial value: in for (int i = 1; ...; i++), the first value used in the body is 1, not 2. The update runs only after the body finishes.

3Steps and Ranges

The header controls the sequence of values the loop control variable takes. Changing the initialization moves the start, changing the Boolean expression moves the end, and changing the update changes the step. Loops can count up by 1 with i++, down with i--, by larger steps with i += 3 or i -= 2, or even multiply with i *= 3.

Whatever the step, the Boolean expression must eventually become false. A loop that counts down needs a condition such as i >= 0, not i <= 10, which would always be true while i decreases. Matching the direction of the update to the direction of the condition is the key to ending the loop.

Figure 3. Changing the initialization, the Boolean expression, or the update changes the sequence of values the loop control variable takes.
Worked Example 3 Other steps

Counting Down by Twos

Predict the output.

Code
for (int i = 10; i >= 0; i -= 2)
{
    System.out.println(i);
}
Output
10
8
6
4
2
0
  1. 1Start at 10, and continue while i >= 0.
  2. 2The update i -= 2 subtracts 2 after each pass: 10, 8, 6, 4, 2, 0.
  3. 3Stopping. After printing 0, i becomes −2 and -2 >= 0 is false.
Result: The output is 10, 8, 6, 4, 2, 0. The update can be any statement that changes the loop control variable, including subtraction and larger steps.
Worked Example 4 Accumulating

Multiplying 1 Through 5

Compute 5! = 1 × 2 × 3 × 4 × 5.

Code
int product = 1;
for (int k = 1; k <= 5; k++)
{
    product = product * k;
}
System.out.println(product);
Output
120
  1. 1Start the product at 1, the multiplicative identity, before the loop.
  2. 2Each pass multiplies by the current k: 1, 2, 6, 24, 120.
Result: The output is 120. A for loop is ideal for accumulating over a known range of values.

4Counting Passes

The most reliable way to find the number of passes is to list the values of the loop control variable that pass the check. For for (int i = 3; i < 12; i += 3), the values 3, 6, and 9 pass and 12 fails, so the body runs 3 times. For a step of 1 from a to b inclusive, the count is b - a + 1; with a strict < it is b - a.

Off by one errors in for loops come from the same sources as in while loops: the starting value and the boundary of the Boolean expression. for (int i = 0; i < 5; i++) and for (int i = 1; i <= 5; i++) both run 5 times, but with different values of i; choose the one whose values the body actually needs.

When a loop is meant to run exactly n times and the values themselves do not matter, the conventional header is for (int i = 0; i < n; i++). Starting at 0 with a strict < makes the count equal to n with no arithmetic, and this pattern will appear constantly once loops are used to visit positions in strings and arrays, whose indices also start at 0.

Worked Example 5 Counting passes

How Many Times Does It Run?

How many times does each loop body run?

Code
int a = 0;
for (int i = 3; i < 12; i += 3)
{
    a++;
}
int b = 0;
for (int i = 1; i < 100; i *= 3)
{
    b++;
}
int c = 0;
for (int i = 5; i < 5; i++)
{
    c++;
}
System.out.println(a + " " + b + " " + c);
Output
3 5 0
  1. 1First loop. i takes 3, 6, 9; at 12 the check fails: 3 passes.
  2. 2Second loop. i takes 1, 3, 9, 27, 81; 243 fails: 5 passes.
  3. 3Third loop. 5 < 5 is false immediately: 0 passes.
Result: The output is 3 5 0. List the values the loop control variable takes; the number of passes is the number of values that pass the check.
Common Mistake 3 · Mismatching Direction and Condition

for (int i = 10; i <= 20; i--) starts at 10 and moves down, so i <= 20 is always true and the loop never ends. A decreasing update needs a lower-bound test such as i >= 0.

5for and while: Equivalent Forms

A for loop can be rewritten into an equivalent while loop, and vice versa. To turn a for loop into a while loop, move the initialization before the loop, use the Boolean expression as the while condition, and place the update as the last statement of the body. Reversing those steps turns a counting while loop into a for loop.

The two forms behave identically, so the choice is about clarity. A for loop suits a known count or range, because the header shows the whole range at once. A while loop suits repetition until a condition changes, when there is no natural counter, such as repeating until a balance reaches a target.

Figure 4. A for loop can be rewritten into an equivalent while loop, and vice versa.
for loopEquivalent while loop
for (int i = 0; i < n; i++) { body }int i = 0; while (i < n) { body i++; }
for (int k = 10; k > 0; k -= 3) { body }int k = 10; while (k > 0) { body k -= 3; }
When to prefer it: a known count or rangeWhen to prefer it: repeat until a condition changes
Worked Example 6 Rewriting

The Same Loop as while

Rewrite for (int i = 2; i <= 8; i += 3) { System.out.println(i); } as a while loop and confirm the output is the same.

for version
for (int i = 2; i <= 8; i += 3)
{
    System.out.println(i);
}
Output
2
5
8
while version
int i = 2;
while (i <= 8)
{
    System.out.println(i);
    i += 3;
}
Output
2
5
8
  1. 1Initialization moves before the loop: int i = 2;.
  2. 2The Boolean expression becomes the while condition.
  3. 3The update becomes the last statement of the body, so it still runs after the rest of the body.
Result: Both print 2, 5, 8. A for loop can be rewritten into an equivalent while loop, and vice versa, by moving the three parts of the header.

6The Loop Control Variable

A loop control variable declared in the header, as in for (int i = 0; ...), exists only within the loop. Using it after the loop does not compile. If the final value is needed afterward, declare the variable before the loop and leave the type out of the initialization: int i; for (i = 0; i < 3; i++).

Changing the loop control variable inside the body is legal but makes the number of passes hard to predict, because the body's change and the header's update both apply. Keep all changes to the control variable in the header so that the header alone describes the loop's range; this is the main reason for loops are easy to read.

Worked Example 7 Scope of the loop variable

Using i After the Loop

Explain the compile error.

Code that does not compile
for (int i = 0; i < 3; i++)
{
    System.out.println(i);
}
System.out.println("last: " + i);
  1. 1Declared in the header. i is declared in the initialization, so it belongs to the loop.
  2. 2After the loop the name i refers to nothing.
  3. 3Fix. If the final value is needed, declare int i; before the loop and write for (i = 0; i < 3; i++).
Result: The program does not compile. A loop control variable declared in the for header can be used only inside the loop.
Common Mistake 4 · Using the Control Variable After the Loop

A variable declared in a for header is not available after the loop. If code after the loop needs the final count, declare the variable before the loop instead.

Four Habits for for Loops

1. Init, Check, Body, Update

Initialization once; update after the whole body.

2. List the Values

Count passes by listing values that pass the check.

3. Match Direction

Decreasing updates need lower-bound conditions.

4. Header Owns the Variable

Change it only in the update; it ends with the loop.

Core Synthesis

A for loop is a type of iterative statement with three parts in its header: the initialization, the Boolean expression, and the update. The initialization statement is only executed once before the first Boolean expression evaluation, and the variable being initialized is referred to as a loop control variable. The Boolean expression is evaluated immediately after the loop control variable is initialized and then following each execution of the update statement until it is false; in each iteration, the update is executed after the entire loop body and before the Boolean expression is evaluated again. A for loop can be rewritten into an equivalent while loop, and vice versa.