Java Arena
Step 5 of 7

Repeating a calculation

The loop variable can take part in the calculation. Here the loop adds up 1 + 2 + 3 + ... up to a number from the input:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int last = Integer.valueOf(scanner.nextLine());
        int sum = 0;
        for (int i = 1; i <= last; i++) {
            sum += i;
        }
        System.out.println("Sum: " + sum);
    }
}
Input
4
Output
Sum: 10

Traced, the sum goes 0, 1, 3, 6, 10. The pattern has the same pieces as summing input: a sum that starts at 0 before the loop, and one addition per round. Only now the added value is i itself, or anything calculated from it.

Your task

Challenge 1 of 3

Read two positive numbers and multiply them without *: add the first number to a sum as many times as the second number says. For the input 6 and 4 the program prints:

24

Challenge 2

Read a number n and print the sum of the squares from 1 to n: 1 times 1, plus 2 times 2, and so on. For the input 3 the program prints:

14

Challenge 3

Read a start and an end, and print the sum of the odd numbers from the start to the end. For the input 3 and 9 the program prints:

Sum of odd numbers: 24