AP® Computer Science A review sheet from Aim for Five (aimforfive.com/csa/units/2/2-8)
Unit 2 · Topic 2.8
2.8 for Loops
A for loop packs a loop's setup, condition and update into one line, which makes it the natural choice when you're counting. This topic covers the exact order the three parts run in, how to count passes, and how to convert between for and while loops.
Key terms
forloop- initialization
- update
- loop control variable
The three parts of the header
A for loop header has three parts, separated by semicolons:
for (int i = 0; i < 4; i++)
{
System.out.print(i * i + " ");
}
System.out.println();
The initialization int i = 0 sets up the loop control variable. The condition i < 4 is the Boolean expression that decides whether to keep going. The update i++ changes the variable. This loop prints 0 1 4 9 .
The exact order of events
Learn this sequence. Tracing questions depend on it.
- 1. The initialization runs once, before anything else.
- 2. The condition is checked. If it's
false, the loop is over. - 3. If it's
true, the whole body runs. - 4. The update runs, after the body.
- 5. Go back to step 2.
for and while are interchangeable
Any for loop can be rewritten as a while loop, and the other way around. Move the initialization above the loop, keep the condition, and put the update at the end of the body. This while loop does exactly what the for loop above does:
int i = 0;
while (i < 4)
{
System.out.print(i * i + " ");
i++;
}
System.out.println();
Use a for loop when you know how many passes you need, like visiting each index of a string. Use a while loop when you're repeating until something happens, like halving a number until it reaches 1. Either choice earns full credit on the exam if the loop is correct, so pick the one that makes your code easier to get right.
Counting passes and scope
The update doesn't have to be i++. It can count down (i--), skip (i += 3) or do anything else that eventually makes the condition false. For a loop like for (int i = a; i < b; i++), the body runs b - a times. With <=, it runs b - a + 1 times. So i from 3 while i < 9 is 6 passes, and i <= 9 is 7. For other updates, like j -= 4, list the values.
A variable declared in the header exists only inside the loop. Using i after the loop is a compile error, because i no longer exists there:
for (int i = 0; i < 3; i++)
{
System.out.println(i);
}
System.out.println(i);
If you need the value after the loop, declare the variable before the loop instead.
Worked examples
Try each one yourself first, then open the solution.
- Example 1
A loop that counts down
What does this code print?
int total = 0; for (int j = 20; j > 5; j -= 4) { total += j; } System.out.println(total);Show the solutionHide the solution
- Step 1: Initialization:
jis 20. The update subtracts 4 after each pass. - Step 2: Check
20 > 5: true,totalbecomes 20, thenjbecomes 16. - Step 3: Check
16 > 5: true,totalbecomes 36, thenjbecomes 12. - Step 4: Check
12 > 5: true,totalbecomes 48, thenjbecomes 8. - Step 5: Check
8 > 5: true,totalbecomes 56, thenjbecomes 4. - Step 6: Check
4 > 5: false. The loop ends after 4 passes.
Answer: It prints
56(that's 20 + 16 + 12 + 8). - Step 1: Initialization:
- Example 2
Rewriting a while loop as a for loop
Rewrite this
whileloop as aforloop that prints the same value.int n = 7; int product = 1; while (n > 1) { product *= n; n -= 2; } System.out.println(product);Show the solutionHide the solution
- Step 1: Find the three parts. The initialization is
int n = 7, the condition isn > 1, and the update isn -= 2, the last line of the body. - Step 2: Put all three in the header, and leave the rest of the body inside.
- Step 3: Check it:
ntakes the values 7, 5, 3, soproductis 7 × 5 × 3 = 105 in both versions. - Step 4:
int product = 1; for (int n = 7; n > 1; n -= 2) { product *= n; } System.out.println(product);
Answer: The
forversion isfor (int n = 7; n > 1; n -= 2)withproduct *= n;in the body. Both print105. - Step 1: Find the three parts. The initialization is
Common mistakes
- Running the update before the body on the first pass. The update always comes after the body.
- Miscounting passes.
i < bstarting atagivesb - apasses;<=adds one more. - Using the loop control variable after the loop when it was declared in the header.
On the exam
- Expect questions that show a
forloop and ask whichwhileloop is equivalent, or how many times a statement runs. Check the starting value, the boundary and the update separately.
Connected topics
Videos
Check yourself
4 questions on 2.8 for Loops. Pick an answer to see if you got it, and why.
Consider the following code segment.for (int i = 2; i <= 10; i += 3)
{
System.out.print(i + " ");
}What is printed as a result of executing the code segment?
Consider the following code segment.for (int k = 0; k < 20; k += 4)
{
System.out.print("*");
}How many asterisks are printed?
Consider the following code segment.for (int j = 5; j > 0; j--)
{
System.out.print(j);
}Which of the following code segments produces the same output?
Consider the following code segment.int total = 0;
for (int i = 1; i <= 4; i++)
{
total += i;
}
System.out.println(total + i);What is printed as a result of executing the code segment?
0 of 4 answered