Skip to the workspace
Pebellslearn by building
Control Flow, Arrays and Strings  ›  Lesson

Loops: for, while and do-while

Loops 13 minA for loop repeats a known number of times, a while loop repeats until its condition becomes false, and a do-while always runs its body at least once.

java / Loops: for, while and do-while

Explore each scene at your own pace.

01 · The rule

The rule

Loops: for, while and do-while

A for loop repeats a known number of times, a while loop repeats until its condition becomes false, and a do-while always runs its body at least once.

Follow loop state through its first, final and zero-iteration cases.

At opening time the barista wants the till to print ticket numbers 1 to 20, and later to keep taking orders until the "closed" key is pressed. The first job has a known count; the second does not. Java has a loop shaped for each.

The rule

Know the count, use for; know the stop condition, use while.

A for loop packs the counter's start, test and step into one line:

for (int ticket = 1; ticket <= 20; ticket++) {
    System.out.println("Ticket " + ticket);
}

It runs in a fixed rhythm: initialise once, then test → body → step, repeated until the test is false.

A while loop repeats as long as its condition holds, and is ideal when you cannot know the count in advance:

int stockCups = 30;
while (stockCups > 0) {
    stockCups -= 4;    // serve a table of four
}

A do-while loop tests at the bottom, so its body always runs at least once, which is handy for "show the menu, then ask whether to continue":

do {
    showMenu();
} while (wantsMore());

When you just want every element of an array or list, the enhanced for reads best: for (int price : pricesCents) { ... }.

Two keywords adjust a loop from inside:

  • break leaves the loop immediately.
  • continue skips the rest of this pass and moves on to the next one.
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.