Menu Close

Sum of Array elements in Java [With Ilustrat..] …FTC

Get array as input and display the sum of array elements as outputs.

S = sum(A) returns the sum of the elements of A along the first array dimension whose size does not equal 1

Input:
Size:  5
Array:  1 2 3 4 5

Output:
Sum = 15
import java.io.*;
import java.util.*;
public class temp{
  public static void main(String[] args){
    int n, sum = 0;
    Scanner s = new Scanner(System.in);
    System.out.println("Enter the Size of array:  ");
    n = s.nextInt();
    int a[] = new int[n];
    System.out.println("Enter elements of array:  ");
    for(int i = 0; i < n; i++)
    {
        a[i] = s.nextInt();
        sum = sum + a[i];
    }
    System.out.println("Sum = "+sum);
  }
}

INPUT_1:
Enter the Size of array:
4
Enter elements of array:
0  2  4  6

OUTPUT:
Sum = 12


INPUT_2:
Enter the Size of array:
5
Enter elements of array:
1  2  3  4  5

OUTPUT:
Sum = 15


INPUT_3:
Enter the Size of array:
7
Enter elements of array:
7  15  62  100  25  89  63

OUTPUT:
Sum = 361


INPUT_4:
Enter the Size of array:
3
Enter elements of array:
1  1  1

OUTPUT:
Sum = 3


INPUT_5:
Enter the Size of array:
6
Enter elements of array:
3  6  9  12  15  18

OUTPUT:
Sum = 63


ILLUSTRATION

eXecuted using javac in linux terminal