Loops: for, while, and do-while
Where you are: Week 0 review > Loops: for, while, and do-while
Try This First
You need to read numbers from a user and stop when they type -1, which is not counted. You do not know how many numbers they will type. Decide which loop shape fits before reading on.
Reveal
A while loop. The count is unknown; the body (the input) decides when to stop. The -1 is a sentinel: a marker value that signals the end of input.
Before You Start
Check each box you can do from memory. A box you cannot check yet is not a problem; it points you to a quick refresher, not a grade.
See Conditionals: if, else, and switch if any of those feel shaky.
Not sure? Take the 60-second self-check.
Try each from memory, then read the answer under it.
- What kind of value does an
iftest require? A boolean expression, one that is eithertrueorfalse. - When does the
elsebranch run? Only when theifcondition isfalse.
What You Need To Walk In With
Walk into the next class able to state these:
- Use
forwhen you know the count before the loop starts. Usewhilewhen the body decides whether to continue. Usedo-whilewhen the body must run at least once. - A
forheader has three parts: init, condition, update. The order is init, check, body, update, check, and the body does not run on the final failed check. - A
whilechecks its condition before every iteration, including the first, so the body may run zero times. - An accumulator is a variable updated once per pass (a running sum, count, or max). Declare it before the loop, update inside, read after.
You should be able to: route an English task to for, while, or do-while, and trace a loop with an accumulator.
How It Works
First time seeing a boolean condition? Open for a 20-second refresher.
A boolean condition is any expression that produces exactly true or false, such as x != 1 or i <= 10. Every loop header tests one of these before each iteration. See Conditionals: if, else, and switch for the full picture.
The for loop: known count
for (int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
// prints: 1 2 3 4 5 6 7 8 9 10
The order is init, then check, then body, then update, then check again. The loop exits the moment the condition is false, and the body does not run for that final check. Reach for for when the task says “do this n times” or “sum the integers from 1 to 50.”
The while loop: unknown count
int x = 10;
while (x != 1) {
if (x % 2 == 0) { x = x / 2; }
else { x = 3 * x + 1; }
System.out.print(x + " ");
}
The condition is checked before every iteration, including the first, so a while body can run zero times. Reach for while when the exit depends on what the body reads or computes (“keep doubling until the value passes one million”).
The do-while loop: at least once
int guess;
do {
guess = readGuess();
} while (guess != secret);
A do-while runs the body first and checks the condition after, so the body always runs at least once. Reach for it when the work must happen before there is anything to test, such as prompting for input the first time.
Choosing the loop shape
Q1: Must the body run at least once, no matter the starting state? YES -> do-while
Q2: Do you know the exact count before the loop? YES -> for
Q3: Does the body decide when to stop? YES -> while
Accumulators
An accumulator carries a result across iterations. Declare it before the loop, or it resets every pass and goes out of scope at the end:
int total = 0;
for (int i = 1; i <= 100; i++) {
total = total + i;
}
System.out.println(total); // 5050
Worked Example: Predict, Then Check
int sum = 0;
for (int i = 1; i <= 4; i++) {
sum = sum + i;
}
System.out.println(sum);
Predict the output before reading on.
Reveal
10. The loop adds 1, then 2, then 3, then 4 into sum, ending at 1 + 2 + 3 + 4 = 10.
A Common Mistake
Declaring the accumulator inside the loop body resets it on every pass and puts it out of scope after the loop, so the running total is lost and a return total; after the loop does not compile. Declare the accumulator before the loop, update it inside, read it after. (Source: BJP (Reges and Stepp), Ch 4.)
Go Deeper (optional)
For the curious: any for loop can be rewritten as a while loop and the reverse, because both reduce to “check a condition, run a body, repeat.” The choice is about which form makes the intent obvious to a reader: for puts the counter machinery in one line when the count is known, while while keeps the focus on a single stopping condition when the count is not.
Check Yourself
Close the notes and answer each one from memory, then reveal it. Pulling an idea back from memory is one of the strongest ways to make it stick.
Check your understanding
You must repeat an action exactly ten times. Which loop shape fits?
A loop reads numbers until the user types -1 (not counted). Which loop, and what is -1 called?
Which loop always runs its body at least once?
int sum=0; for(int i=1;i<=4;i++){ sum=sum+i; } print(sum). What prints?
Where do you declare a sum accumulator?