Sum an Array (var, Java 10)

Problem

Print the sum of the array. Use a long for the total, because the sum can be larger than an int.

Constraints

  • 1 <= n <= 10^5
  • |a[i]| <= 10^9

Examples

Input

3
1 2 3

Output

6

Solutions

AlternativeTime O(n)Space O(1)

The Java 8 style writes the type of each local variable by hand.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process an array.
 * Input   : n, then n integers.
 * Output  : The sum.
 * Approach: Loop and add.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static long solve(int[] a) {
        // Step 1: In Java 8 we must write the type of every variable.
        long total = 0;
        for (int value : a) {
            total += value;
        }
        return total;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(solve(a));
    }
}
Hints (1)
  1. What type should the total have?