Find sum of elements of array

You are given an array of integers of size N *N. Find the sum of elements in array?
Accept the input from console.
This is the simple array program and asked in entry level college exams.

Input
The first line of input consists of an integer NN. The next line contains N * N space-separated integers representing the array elements.

Sample:
6
111 3 7 23 98 56

Output:
298

Java program:

import java.util.Scanner;

public class ArraySum {

	private static long calculateArraySum(int[] arr) {
		long sum = 0;
		for (int i = 0; i < arr.length; i++) {
			sum += arr[i];
		}
		return sum;
	}

	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();

		int arr[] = new int[n];
		for (int i = 0; i < n; i++) {
			arr[i] = in.nextInt();
		}

		System.out.println(calculateArraySum(arr));
		in.close();
	}
}

I hope you liked the solution.
Please comment for questions or doubts.

Leave a Reply