jario_
Back to overview

Chapter 3

Loops

A loop repeats a block as long as a condition holds. That's how you count to 1000 without writing 1000 lines, or keep reading input until a certain value comes.

The for loop

Use a for loop when you know in advance how often something should happen. The parentheses contain three parts, separated by semicolons:

for (int i = 1; i <= 5; i++) { ... }
  1. Start: int i = 1 creates the counter.
  2. Condition: as long as i <= 5 is true, the block runs.
  3. Step: i++ increases i by 1 after each pass.

Often a variable outside the loop collects a result, such as a sum. sum += i is short for sum = sum + i.

You can change the code and run it again.

while and do-while

while checks the condition before each pass. That fits when you don't know how often the loop runs, only when it should stop. If the condition is already false at the start, the block doesn't run at all.

do { ... } while (...); checks only after the pass, so the block runs at least once. A typical use is an input that's repeated until it's valid.

You can change the code and run it again.

The input contains two invalid numbers (15 and 0), so the program asks three times.

Nested loops, break and continue

A loop can sit inside another one. For every pass of the outer loop, the inner one runs all the way through, like the rows and columns of a table. print writes without a line break, and an empty println() ends the line.

Two commands change the flow:

  • break ends the loop immediately.
  • continue skips the rest of the block and goes on with the next pass.
You can change the code and run it again.

Common mistakes

  • Endless loop

    If nothing in the loop changes the condition, it never stops:

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

    In Jario the program is then stopped after a time limit.

  • One too many or too few

    i < 5 runs for 0 to 4, i <= 5 for 0 to 5. Check with the smallest case whether the first and last pass are right.

  • Semicolon after for or while

    for (int i = 0; i < 5; i++); has an empty loop body. The block after it runs only once. With while (...); the program can even get stuck.

  • Creating the counter inside the loop

    If int sum = 0; is inside the loop, the sum starts at 0 again on every pass. Anything that counts across all passes belongs before the loop.