Java program to find sum & average of an array

Let’s learn java program to find sum & average of an array.

Java program to find sum & average of an array

To find sum and average of an array first user enters (total) number of elements using nextInt() method of Scanner class.

This number is stored in integer variable “number”. Then this number is assigned to integer array “arrNum”.

Now user enters each elements or numbers which gets stored in integer array ‘arrNum’ and meanwhile calculate sum in for loop.

This sum is divided by total number of elements in array to calculate average.

Here’s the java program.

import java.util.Scanner;
public class SumAverageArrayDemo
{
   public static void main(String[] args)
   {
      int number, sum = 0;
      float average;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter number of elements : ");
      number = sc.nextInt();
      int[] arrNum = new int[number];
      System.out.println("Enter " + number + " elements : ");
      for(int a = 0; a < number ; a++)
      {
         arrNum[a] = sc.nextInt();
         sum = sum + arrNum[a];
      }
      System.out.println("Sum is : " + sum);
      // average of an array
      average = (float)sum / number;
      System.out.println("Average is : " + average);
      sc.close();
   }
}


Output:

java program to find sum & average of an array