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(System.in);
  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. }

Output:

$ javac Sum_Average.java
$ java Sum_Average
 
Enter no. of elements you want in array:5
Enter all the elements:
4
7
6
9
3
Sum:29
Average:5.8

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement

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

👉 For weekly programming practice and certification updates, join Sanfoundry’s official WhatsApp & Telegram channels
advertisement
Manish Bhojasia – Founder & CTO at Sanfoundry

I’m Manish, Founder & CTO at Sanfoundry, with 25+ years of experience across Linux systems, SAN technologies, advanced C programming, and building large-scale, performance-driven learning and certification platforms focused on clear skill validation.

LinkedIn  ·  YouTube MasterClass  ·  Telegram Classes  ·  Career Guidance & Conversations