← Java from Scratch Lesson 16 of 88 · 10 XP

The while loop

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}

do {
    // runs at least once
} while (condition);

To read numbers while there are any: while (in.hasNextInt()) { int x = in.nextInt(); … }.

Task. Read a natural number n. Until n becomes 1: if it's even, halve it; if it's odd, make it 3n + 1. Print the number of steps (the Collatz conjecture).

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.