Java program to find sum & average of an array

In this post we going to learn java program to find sum & average of an array.

In this java program user enters elements. Next in for loop we calculate sum. Meanwhile divide by number of elements in array to calculate average.

Also read – comments in java

Here’s the java program to calculate sum & average of an array,

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.print("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 = (float)sum / number;
      System.out.println("Average is : " + average);
      sc.close();
   }
}

Output:

java program to find sum & average of an array