Friday, January 20, 2017

Sum of Array Elements in Java

Tags

Following program is used to find sum of array elements :

import java.util.*;
public class Gndec {

 
    public static void main(String[] nt)
    {   Scanner input=new Scanner(System.in);   //for user input
    System.out.println("Enter Number of Elements");
    int n=input.nextInt();    //no of elements
    int[] a=new int[n];       //allocating space for n elements
    System.out.println("Enter The Elements");
        for(int i=0;i<n;i++)
       {
         a[i]=input.nextInt();       //storing all values
       }
        int sum=0;
        for(int i=0;i<n;i++)
        {
            sum=sum+a[i];
        }
        System.out.println("Sum of Elements="+sum);
    }
}

Output: