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

In java average of array 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 average of array and sum 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 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