A for loop puts a loop's three parts in one header: for (initialization; condition; update). The initialization runs once, the condition is tested before every pass, and the update runs after every pass. for (int i = a; i < b; i++) runs its body b − a times when b ≥ a, and changing < to <= adds one more pass.
Quick check
With int k = 0, how many times does the body of while (k < 3) { k++; } run?Show answerHide answer
3 times, with
kequal to 0, 1 and 2. Whenkreaches 3,3 < 3isfalse.After int i = 5; i++; what is i?Show answerHide answer
i++adds 1 toi.
How many whole numbers are there from 3 to 7 inclusive?Show answerHide answer
5: the numbers 3, 4, 5, 6 and 7. Counting both ends gives 7 − 3 + 1.
Know these already? Jump to the practice questions
What you'll be able to do
- Identify the initialization, condition and update of a
forloop, and when each one runs. - Calculate how many times a
forloop body runs from its bounds and step. - Rewrite a
forloop as an equivalentwhileloop, and back. - Spot off-by-one errors caused by
<versus<=or by the starting value.
Key terms
Loop control variable
The variable that a loop's condition tests and its update changes, such as i in for (int i = 0; i < 5; i++).
- In plain English
- The counter that decides when the loop stops.
- Don't write
- "The loop control variable changes before the first pass."
Off-by-one error
A loop that runs one pass too many or too few, usually because of the starting value or < versus <=.
- In plain English
- Miscounting by exactly one.
- Don't write
- "
i <= nandi < ngive the same number of passes."
Scope
The part of a program where a variable can be used. A variable declared in a for header can be used only inside that loop.
- In plain English
- Where a variable's name works.
- Don't write
- "The loop variable keeps its value after the loop ends."
What does each part of a for loop do?
A for header holds three parts, separated by semicolons:
- The initialization runs once, before anything else.
- The condition is tested before every pass; when it is
false, the loop ends. - The update runs after every pass, then the condition is tested again.
for (int i = 1; i <= 4; i++)
{
System.out.print(i * i + " ");
}
The body runs for i = 1, 2, 3 and 4, printing 1 4 9 16, with i++ after each pass; at 5, 5 <= 4 is false. So the condition is tested 5 times and the update runs 4 times.
Because i is declared in the header, its scope is the loop: a statement after the loop that uses i does not compile. The for syntax is not on the Java Quick Reference: Learn this.
Check yourself
Show answerHide answer
No. The first pass uses the initial value, and the update runs only after each pass ends.
How many times does the body run?
For a step of 1, use the bounds:
| Header | Passes |
|---|---|
for (int i = a; i < b; i++) | b − a |
for (int i = a; i <= b; i++) | b − a + 1 |
for (int i = b; i > a; i--) | b − a |
If a formula gives a negative number, the body runs 0 times.
For any other step, list the values of the loop control variable and count them. for (int i = 0; i < 20; i += 3) takes i through 0, 3, 6, 9, 12, 15 and 18, so the body runs 7 times.
Counting passes measures work: for (int i = 0; i < n; i++) runs n times, so doubling n doubles the passes.
Key idea
With <, the end value is left out; with <=, it is included, which adds one pass.
Check yourself
Show answerHide answer
6 times: 8 − 3 + 1 = 6, for i = 3, 4, 5, 6, 7 and 8.
How do you rewrite a for loop as a while loop?
Move each part to its own place:
int sum = 0;
for (int i = 0; i < 5; i++)
{
sum = sum + i;
}
int sum = 0;
int i = 0;
while (i < 5)
{
sum = sum + i;
i++;
}
The initialization goes before the while, the condition stays in the parentheses, and the update becomes the last statement of the body. Both loops make sum 10.
One difference remains: in the while version, i is declared outside the loop, so it still exists afterward, holding 5. To turn a while loop into a for loop, reverse the moves: the start value, the condition and the last-line update go into the header.
Check yourself
Show answerHide answer
- The loop stops when
i < 5becomesfalse, which first happens at 5.
Where do off-by-one errors come from?
An off-by-one error comes from the starting value or from the comparison. To print 1 to 10:
| Header | Values of i | Problem |
|---|---|---|
for (int i = 1; i <= 10; i++) | 1 to 10 | none |
for (int i = 1; i < 10; i++) | 1 to 9 | one pass short |
for (int i = 0; i <= 10; i++) | 0 to 10 | one pass extra |
Check the first and last values the loop variable takes.
String indexes are a common case. The last index of s is s.length() - 1, so a loop over every character uses i < s.length(). With i <= s.length(), the last pass calls s.substring(i, i + 1) with i equal to the length, which throws a StringIndexOutOfBoundsException.
Check yourself
Show answerHide answer
0, 1, 2 and 3: four values. The end value 4 is left out.
Worked example 1: Trace a loop with a step of 3
Question: What is printed when this code segment runs?
int total = 0;
for (int i = 2; i <= 10; i += 3)
{
total = total + i;
}
System.out.println(total);
What tells you the method
A step other than 1, so trace the loop control variable with a table.
Step 1: Trace each pass.
Pass ii <= 10?totalafter the pass1 2 true2 2 5 true7 3 8 true15 11 false: stopWhyThe update
i += 3runs after each pass, and the condition is tested before the next one.Step 2: Print the result.
After the loop,
totalis 15.WhyThe
printlnis outside the loop, so it runs once.
Check it
2 + 5 + 8 = 15, and the next value, 11, is past 10, so no pass was missed.
Answer
15
Worked example 2: Rewrite a while loop as a for loop
Question: Rewrite this while loop as a for loop, then state what the code prints.
int n = 30;
int count = 0;
while (n > 0)
{
count++;
n = n - 7;
}
System.out.println(count);
What tells you the method
A loop variable with a clear start, condition and last-line update, so it fits a for header.
Step 1: Find the three parts.
The initialization is
int n = 30, the condition isn > 0, and the update isn = n - 7, whichn -= 7shortens.WhyEach part of a
whileloop has one place in aforheader.Step 2: Write the
forloop.int count = 0; for (int n = 30; n > 0; n -= 7) { count++; } System.out.println(count);WhyThe update leaves the body and joins the header, so the body keeps only
count++.Step 3: Trace it.
ntakes 30, 23, 16, 9 and 2, then -5, which failsn > 0, so the body runs 5 times.WhyEach value that passes the condition is one pass.
Check it
The while version also makes 5 passes; only the scope differs, since n no longer exists after the for loop.
Answer
5
Worked example 3: Choose the header for a reverse loop
Question: The code segment should print the characters of word in reverse order. Which header completes it?
String word = "stone";
String rev = "";
for ( /* header */ )
{
rev = rev + word.substring(i, i + 1);
}
System.out.println(rev);
- A)
int i = word.length(); i >= 0; i-- - B)
int i = word.length() - 1; i > 0; i-- - C)
int i = word.length() - 1; i >= 0; i-- - D)
int i = 0; i < word.length(); i++
What tells you the method
Loop bounds over String indexes, so check each option's first and last i.
Step 1: Find the indexes needed.
"stone" has length 5, so the indexes run from 4 down to 0.
WhyThe last index is always
length() - 1.Step 2: Test each option's first and last values.
C starts at 4 and stops after 0, so it builds "enots". A starts at 5, and
substring(5, 6)throws aStringIndexOutOfBoundsException. B stops before index 0 and builds "enot". D counts up and builds "stone".WhyOff-by-one errors show up at the ends of the range.
Check it
C's passes are i = 4, 3, 2, 1, 0, which is 5 passes for 5 characters.
Answer
C
Your turn
Question: How many times does the body of this loop run?
for (int k = 5; k < 50; k *= 2)
{
System.out.println(k);
}
Step 1: List the first values.
kstarts at 5, and the update doubles it after each pass: 5, then 10.Step 2: Your go: keep doubling until the condition fails, then count the passes.
Show the full solutionHide the solution
Step 2. The values of k are 5, 10, 20 and 40. The next value is 80, and 80 < 50 is false, so the loop ends after 4 passes.
Answer: 4
Traps
Trap
for (int i = 0; i <= n; i++) runs n times.
It seems right because the loop goes up to n. But it includes both 0 and n, so it runs n + 1 times; i < n gives n passes.
How many times does the body of for (int i = 0; i <= 5; i++) run?
6 times, for i = 0, 1, 2, 3, 4 and 5.
Trap
A loop control variable declared in the header can be used after the loop.
It seems right because the variable clearly had a value inside the loop. But its scope ends with the loop. To use the final value, declare it before the loop.
What is i after int i; for (i = 0; i < 4; i++) { } runs?
- Here
iis declared before the loop, so it still exists, and the loop stopped wheni < 4becamefalse.
What's examined
On the AP® Computer Science A exam (Unit 2: Selection and Iteration), multiple-choice questions ask how many times a for loop body runs, what it prints, which header gives a described result, or which while loop matches it. In free response, you choose for loop bounds in your own methods, where an off-by-one bound changes the result or throws an exception.
Practice questions
- Apply What is printed when this code segment runs?
for (int i = 3; i > 0; i--)
{
System.out.print(i + " ");
}
System.out.println("go");
Show answer
Answer: 3 2 1 go
Marking points:
- The body prints 3, 2 and 1, each followed by a space; at 0,
0 > 0isfalse. - The
printlnafter the loop adds go on the same line.
- Apply How many times does the body of
for (int j = 1; j <= 30; j += 4)run?
Show answer
Answer: 8
Marking points:
jtakes the values 1, 5, 9, 13, 17, 21, 25 and 29.- The next value, 33, fails
j <= 30.
- Apply Which
forloop prints the same numbers as thiswhileloop?
int m = 1;
while (m < 100)
{
System.out.print(m + " ");
m = m * 3;
}
Each option has the body { System.out.print(m + " "); }.
- A)
for (int m = 3; m < 100; m *= 3) - B)
for (int m = 1; m < 100; m *= 3) - C)
for (int m = 1; m <= 100; m++) - D)
for (int m = 1; m * 3 < 100; m *= 3)
Show answer
Answer: B. It keeps the start value 1, the condition m < 100 and the update that triples m, so it prints 1 3 9 27 81, as the while loop does.
Why the others are wrong:
- A has the wrong starting value, so 1 is never printed.
- C assumes the update is always
++, so it prints every number from 1 to 100. - D tests the next value instead of the current one, so it stops before printing 81.
- Exam-style The method should return how many times "a" appears in
s, but it throws an exception. Give the number of the line that causes this.
1: public static int countA(String s)
2: {
3: int count = 0;
4: for (int i = 0; i <= s.length(); i++)
5: {
6: if (s.substring(i, i + 1).equals("a"))
7: {
8: count++;
9: }
10: }
11: return count;
12: }
Show answer
Answer: Line 4.
Marking points:
- On the last pass
iequalss.length(), sosubstring(i, i + 1)is out of range and throws aStringIndexOutOfBoundsException. - Changing
<=to<on line 4 stops at the last index;countA("banana")then returns 3.
- Exam-style A loop body should run exactly 10 times. Which header does that?
- A)
for (int i = 0; i <= 10; i++) - B)
for (int i = 1; i < 10; i++) - C)
for (int i = 10; i >= 0; i--) - D)
for (int i = 5; i < 15; i++)
Show answer
Answer: D. i runs from 5 to 14, and 15 − 5 = 10 passes.
Why the others are wrong:
- A starts at 0 and includes 10, so it runs 11 times.
- B starts at 1 but uses
<, so it runs only 9 times. - C counts down from 10 to 0 inclusive, so it runs 11 times.
- Exam-style What happens when this code segment is compiled and run?
int total = 0;
for (int i = 0; i < 4; i++)
{
total = total + i;
}
System.out.println(total + i);
- A) It does not compile, because
iis used outside its scope. - B) It prints 6.
- C) It prints 10.
- D) It prints 9.
Show answer
Answer: A. i is declared in the for header, so it exists only inside the loop, and the last line cannot use it.
Why the others are wrong:
- B assumes
iis back to 0 after the loop, giving 6 + 0. - C assumes
istill exists after the loop with its final value, 4. - D assumes
ikeeps 3, its value in the last pass.
- Recall What is the name for a mistake that makes a loop run one pass too many or one too few?
Show answer
Answer: Off-by-one error
Marking points:
- It usually comes from the starting value, or from
<where<=is needed, or the reverse.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- Initialization once; condition before each pass; update after each pass.
aup tobwith<gives b − a passes; with<=it gives b − a + 1.- For other steps, list the loop variable's values and count them.
- To change a
forloop into awhileloop, put the initialization before it and the update at the end of the body. - A variable declared in the header disappears after the loop.
- Check the first and last values the loop variable takes to catch off-by-one errors.