Java Program to Find Sum of Array Elements

This is a Java Program to Accept Array Elements and Calculate Sum. An array is a group of like-typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. Aspecific element in an array is accessed by its index.

Enter the size of array and then enter all the elements of that array. Now we calculate the sum of elements of the array with the help of for loop.

Here is the source code of the Java Program to Accept Array Elements and Calculate Sum. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1. import java.util.Scanner;
  2. public class Array_Sum
  3. {
  4.     public static void main(String[] args) 
  5.     {
  6.         int n, sum = 0;
  7.         Scanner s = new Scanner(;
  8.         System.out.print("Enter no. of elements you want in array:");
  9.         n = s.nextInt();
  10.         int a[] = new int[n];
  11.         System.out.println("Enter all the elements:");
  12.         for(int i = 0; i < n; i++)
  13.         {
  14.             a[i] = s.nextInt();
  15.             sum = sum + a[i];
  16.         }
  17.         System.out.println("Sum:"+sum);
  18.     }
  19. }


$ javac
$ java Array_Sum
Enter no. of elements you want in array:5
Enter all the elements:

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.