Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Loops

A loop repeats a block of code while a condition holds. Without loops, printing the numbers from 1 to 100 would take a hundred identical lines. One run of the loop body is called an iteration.

while

The while loop checks its condition before each iteration. As long as it is true, the body runs again and again:

void main() {
    int count = 1;
 
    while (count <= 3) {
        IO.println("Iteration " + count);
        count++;
    }
}

Output:

Iteration 1
Iteration 2
Iteration 3

The count variable must change inside the loop. Otherwise the condition stays true forever and you get an infinite loop.

do-while

do-while runs the body first and checks the condition afterwards. So the body runs at least once, even if the condition is false from the start:

void main() {
    int attempts = 5;
 
    do {
        IO.println("Attempt " + attempts);
        attempts++;
    } while (attempts < 3);
}

Output:

Attempt 5

for

The for loop keeps all the control in one line: the counter's starting value, the condition and the step. It is the most common loop when the number of repetitions is known in advance:

void main() {
    for (int i = 1; i <= 5; i++) {
        IO.print(i + " ");
    }
    IO.println();
}

Output:

1 2 3 4 5

First int i = 1 runs, then i <= 5 is checked before each iteration, and i++ runs after each one. The step can be anything, for example i += 2, or i-- to count down.

Accumulating a result

Often a loop does not just print values but accumulates a result in a variable declared before the loop:

void main() {
    int sum = 0;
    for (int i = 1; i <= 100; i++) {
        sum += i;
    }
    IO.println(sum);
}

Output:

5050

for-each

An array is a set of values of one type under one name; the lesson on arrays covers it in detail. The easiest way to go through all its elements is the for-each loop: the variable to the left of the colon gets each element in turn:

void main() {
    String[] names = {"Anna", "Oleg", "Maria"};
 
    for (String name : names) {
        IO.println("Hello, " + name);
    }
}

Output:

Hello, Anna
Hello, Oleg
Hello, Maria

for-each does not give you the element's index. If you need the index, use a regular for.

Common mistake

Array indexes start at zero, so the last element has index length - 1. Using <= instead of < makes the loop go past the end of the array:

void main() {
    int[] prices = {10, 20, 30};
 
    for (int i = 0; i <= prices.length; i++) {
        IO.println(prices[i]);
    }
}

Output:

10
20
30
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3

To walk through an array by index, write i < prices.length.

Thanks for reading!

Donate to the site — we work hard for you.