Command Palette

Search for a command to run...

Back to the lesson: Topic 2.5 — while and do-while Loops
Core Java · Example 3 of 5

The Collatz sequence: loop until a condition

Nobody has proved this loop ends for every starting number (the Collatz conjecture), but it has for every number ever tried.

A while loop repeats a block as long as a condition stays true, checking the condition before each pass, so it may run zero times. A do-while checks after each pass, so its body always runs at least once.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Using a while loop, print the powers of 2 that are less than 100, on one line separated by spaces.

02

Using a while loop, check whether 12321 is a palindrome number (reads the same backwards).

03

Using a do-while loop, print the numbers from 5 down to 1, then Lift off!.

Explain it without notes

01

What is the difference between while and do-while? Give a situation suited to each.

02

What three things does a counting while loop need, and what goes wrong if each is missing?

03

Why is code after while (true) { ... } with no break a compile error?

04

When would you choose a while loop over a for loop?

The Collatz sequence: loop until a condition
Sign in to run this example in your browser.

Expected output

6 -> 3 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1
Reached 1 in 8 steps