JAVA · ОСНОВЫ · LESSON 15

Put the whole row together.

Array and sum · about 16 minutes

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

Start from scratch.

To collect the amount, get int total = 0. For each number, add it to total.

int total = 0;
for (int number : nums) {
    total += number;
}

✦ The += sign adds a number to what has already happened.

STEP 2

Find out after the loop.

When the loop is completed, total stores the sum of all numbers. Show it through println.

int[] nums = {2, 3};
int total = 0;
for (int number : nums) { total += number; }
System.out.println(total);
The piggy bank
0beginning+ 2first+ 35

✦ The result is 5.

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, 3};
        int total = 0;
        for (int number : nums) {
            total += number;
        }
        System.out.println(total);
    }
}
Open the editor for class work
HOMEWORK

Solve it yourself

Create int[] nums from 1, 2, 3. Start with int total = 0, add each number using for-each and output total.

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

Opening up your homework