Java course

For, while, and do/while loops

1.4.1 — For, while, and do/while loops

A loop repeats a block of code. Learn when its condition is checked and how its variables change.

int count = 0; creates a whole-number variable. count = count + 1; replaces it with a value one larger. A comparison such as count < 3 gives true or false. System.out.println(...) prints a value. Each example declares its own inputs.

A for loop

The three parts inside for (...) are separated by semicolons:

for (int i = 1; i <= 3; i = i + 1)
  1. Create i with value 1, once.
  2. Before each repetition, check i <= 3. If false, stop.
  3. Run the block, then update i with i = i + 1.

Braces group the repeated statements. The loop prints before it updates i.

Trace the same loop

i before checki <= 3Action
1truePrint 1, update i to 2
2truePrint 2, update i to 3
3truePrint 3, update i to 4
4falseStop without printing

The condition is checked four times, but the body runs three times.

Less than or less than or equal to

i < 3 excludes 3. i <= 3 includes it. Choosing the wrong boundary is an off-by-one error: the loop repeats one time too few or too many.

The next cell starts at 1 and uses < 3. Compare its output with the previous loop.

A while loop

while checks its condition before every repetition. Put the starting value before the loop, and the update inside its body.

The next cell prints the same numbers as the first for loop. The update makes current move toward the point where the condition becomes false.

A loop can run zero times

If the first condition check is false, for and while skip their bodies. The next cell sets the limit to 0, so it only prints the message after the loop.

A do/while loop checks afterward

do/while runs its body first, then checks whether to repeat. It always runs at least once. Its final condition ends with a semicolon.

In the next cell, doCurrent starts at 1 and the limit is 0. It still prints 1 once before checking the condition.

Keep a running total

An accumulator stores a result as the loop progresses. Start sum at 0, then add each current number to it.

isum beforesum after sum + i
101
213
336

Run this cell and compare the final sum with the table.

Practice: print three numbers

The next loop currently stops before printing 3. Change only < to <= in its condition. Run it: it should print 1, 2, and 3, on separate lines.

Hint

The corrected condition is i <= practiceLimit. Leave the starting value and update unchanged.

Worked solution
int practiceLimit = 3;
for (int i = 1; i <= practiceLimit; i = i + 1) {
    System.out.println(i);
}

Check zero, one, and several repetitions

In your completed cell, change only practiceLimit:

practiceLimitExpected output
0No output
11
31, then 2, then 3

A variable declared in the for header, such as i, belongs to that loop. Declare a total outside the loop if you need to print it afterward.

Enable JavaScript to run the Java notebook.