JAVA · ОСНОВЫ · LESSON 14

Go around the whole array.

for-each loop · about 14 minutes

Learning with progressRead the summary for free. To save the work, log in to the account.
STEP 1

Take every element.

The for-each loop takes all the numbers from the array in turn. In brackets on the left is the name of the current number, on the right is the name of the array.

int[] nums = {2, 4};
for (int number : nums) {
    System.out.println(number);
}

✦ 2 and 4 will appear.

STEP 2

The colon says «из»

For each int number from nums. It is convenient when all elements are needed and their numbers are not important.

int[] nums = {2, 4};
for (int number : nums) {
    System.out.println(number);
}

✦ Inside the loop, use the current number.

IN-CLASS PRACTICE

Type the code yourself

Type an example manually. Check the signs and brackets.

public class Main {
    public static void main(String[] args) {
        int[] nums = {2, 4};
        for (int number : nums) {
            System.out.println(number);
        }
    }
}
Open the editor for class work
HOMEWORK

Solve it yourself

Create int[] coins from 1, 3, 5. With for-each, output each number. The current element is called coin.

The answer is hidden. Use similar examples from the lesson notes.

Opening up your homework