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
The Java 8 style writes the type of each local variable by hand.
/*
* 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)
- What type should the total have?