Java Program to Find Sum and Average of All Elements in an Array

This is a Java Program to Calculate Sum & Average of an Array.

Enter size of array and then enter all the elements of that array. Now using for loop we calculate sum of elements of array and hence we divide it by number of elements in array to get average.

Here is the source code of the Java Program to Calculate Sum & Average of an Array. 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 Sum_Average
  3. {
  4.     public static void main(String[] args) 
  5.     {
  6.         int n, sum = 0;
  7.         float average;
  8.         Scanner s = new Scanner(;
  9.         System.out.print("Enter no. of elements you want in array:");
  10.         n = s.nextInt();
  11.         int a[] = new int[n];
  12.         System.out.println("Enter all the elements:");
  13.         for(int i = 0; i < n ; i++)
  14.         {
  15.             a[i] = s.nextInt();
  16.             sum = sum + a[i];
  17.         }
  18.         System.out.println("Sum:"+sum);
  19.         average = (float)sum / n;
  20.         System.out.println("Average:"+average);
  21.     }
  22. }


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

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

Note: Join free Sanfoundry classes at Telegram or Youtube

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.