AP® Computer Science A review sheet from Aim for Five (aimforfive.com/csa/units/2/2-7)
Unit 2 · Topic 2.7
2.7 while Loops
A while loop repeats a block of code as long as a condition stays true. This topic covers how while loops run, how to trace them, and the three classic loop bugs: a loop that never runs, a loop that never stops, and a loop that runs one time too many or too few.
Key terms
- iteration
whileloop- loop condition
- infinite loop
- off-by-one error
How a while loop runs
Iteration means repeating a block of code. A while loop is the simplest kind of iteration. It has a condition and a body:
int savings = 40;
int weeks = 0;
while (savings < 100)
{
savings += 25;
weeks++;
}
System.out.println(weeks + " weeks, $" + savings);
Here's the cycle. Java checks the condition. If it's true, the whole body runs, then Java goes back and checks the condition again. As soon as the condition is false, the loop ends and the program continues with the statement after the loop.
The condition is checked before every pass, including the first. Each pass through the body is called an iteration.
In the example, savings goes 40, 65, 90, 115. After the third pass, 115 < 100 is false, so the loop stops and it prints 3 weeks, $115. Notice the loop doesn't stop the moment savings passes 100: it only stops when the condition is checked.
Zero passes and infinite loops
If the condition is false the first time it's checked, the body never runs at all. A while loop can run zero times.
If nothing in the body ever makes the condition false, the loop never ends. That's an infinite loop. The usual cause is forgetting to update the variable in the condition, like leaving out weeks++ in a loop that tests weeks, or updating it in the wrong direction.
So for every while loop, check three things: the variable in the condition starts at a sensible value, the body changes it, and the change moves toward making the condition false.
Off-by-one errors
An off-by-one error is a loop that runs one time too many or one time too few. It usually comes from using < where you needed <=, or starting at 1 instead of 0. To check a loop's boundaries, trace the first pass and the last pass carefully.
int i = 1;
int sum = 0;
while (i < 10)
{
sum += i;
i++;
}
System.out.println(sum);
If this was meant to add 1 through 10, it's off by one: i < 10 stops before 10 is added, so it prints 45 instead of 55. The condition should be i <= 10.
Tracing with a table
To trace a loop, make a table with a column for each variable and a row for each check of the condition. Fill in values as they change. It's slower than doing it in your head, but it's how you avoid losing track on the exam.
Worked examples
Try each one yourself first, then open the solution.
- Example 1
Tracing a while loop
What does this code print?
int k = 1; while (k <= 5) { System.out.print(k + " "); k += 2; } System.out.println("| k is " + k);Show the solutionHide the solution
- Step 1:
kstarts at 1. Check1 <= 5: true. Print1, thenkbecomes 3. - Step 2: Check
3 <= 5: true. Print3, thenkbecomes 5. - Step 3: Check
5 <= 5: true. Print5, thenkbecomes 7. - Step 4: Check
7 <= 5: false. The loop ends, and the last line prints| k is 7on the same line, because the loop usedprint, notprintln.
Answer: It prints
1 3 5 | k is 7. - Step 1:
- Example 2
Counting passes
How many times does the loop body run, and what is printed?
int n = 50; int steps = 0; while (n > 1) { n = n / 2; steps++; } System.out.println(steps);Show the solutionHide the solution
- Step 1: Integer division drops the remainder. Track
nandsteps: - Step 2: 50 becomes 25 (steps 1), 25 becomes 12 (steps 2), 12 becomes 6 (steps 3), 6 becomes 3 (steps 4), 3 becomes 1 (steps 5).
- Step 3: Now
1 > 1is false, so the loop stops.
Answer: The body runs 5 times, and it prints
5. - Step 1: Integer division drops the remainder. Track
Common mistakes
- Forgetting to update the loop variable inside the body, which makes an infinite loop.
- Thinking the loop stops the instant the condition becomes false in the middle of the body. The whole body finishes first; the condition is only checked at the top.
- Off-by-one errors from
<versus<=. Trace the last pass to be sure.
On the exam
- Multiple-choice questions often ask how many times a loop body runs, or what a variable's value is after the loop. Make a trace table instead of guessing.
- Use a
whileloop when you don't know in advance how many passes you need, such as repeating until a value reaches a target.
Connected topics
Videos
Check yourself
4 questions on 2.7 while Loops. Pick an answer to see if you got it, and why.
Consider the following code segment.int n = 1;
int count = 0;
while (n < 50)
{
n *= 3;
count++;
}
System.out.println(count + " " + n);What is printed as a result of executing the code segment?
Consider the following code segment.int k = 10;
int sum = 0;
while (k < 5)
{
sum += k;
k++;
}
System.out.println(sum + " " + k);What is printed as a result of executing the code segment?
Which of the following code segments results in an infinite loop?
Consider the following method./** Precondition: n >= 1
* Returns 1 + 2 + ... + n
*/
public static int sumTo(int n)
{
int sum = 0;
int k = 1;
while (k < n)
{
sum += k;
k++;
}
return sum;
}The method does not work as intended. For example, sumTo(4) returns 6 instead of 10. Which change makes the method work as intended?
0 of 4 answered