Sum and average of values in an array in java

Hello guys!! Welcome to flower brackets blog. In this post we going to learn sum and average of values in an array in java.

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

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:

Sum and average of values in an array in java

Related Posts