Java Average Of Array

Hey guys!! Welcome to flower brackets blog. In the following post you will learn java average of array.

java average of array

 

Here I am going to show you how to find the average of an array in java of predefined array elements. So, let us get into program to find the average of numbers using array,

public class AverageArrayDemo
{
   public static void main(String[] args) 
   {
      double num[] = {30,12.5,14,24.56,19,89.45,128};
      double total = 0;

      for(int a = 0; a < num.length; a++)
      {
         total = total + num[a];
      }

      double average = total / num.length;      
      System.out.println("Average is : " + average);
   }
}

Output:

Average is : 45.35857142857143


Java program to calculate average using array

Here we are going to learn how to calculate average of array input. For this we are using Scanner class to get all the numbers from user,

Also Read – Java Array Copy Of Range Method

import java.util.Scanner;

public class AverageArrayExample
{
   public static void main(String[] args) 
   { 
      System.out.println("Please enter the numbers you want to find average : ");
      Scanner sc = new Scanner(System.in);
      int num = sc.nextInt(); 
      double arrAverage[] = new double[num];
      double sum = 0;

      for(int a = 0; a < arrAverage.length; a++)
      {
         System.out.print("Please enter no." + (a + 1) + " : ");
         arrAverage[a] = sc.nextDouble();
      }

      for(int a = 0; a < arrAverage.length; a++)
      {
         sum = sum + arrAverage[a];
      }
      double average = sum / arrAverage.length;
      System.out.format("The average of array is : %.2f", average);
      sc.close();
   }
}

Output:

Please enter the numbers you want to find average : 5
Please enter no.1 : 53.5
Please enter no.2 : 66.4
Please enter no.3 : 58.7
Please enter no.4 : 26.8
Please enter no.5 : 68.8
The average of array is : 54.84

 


Conclusion

That’s it guys. This all about java program to calculate average using array.

You can subscribe to my blog flower brackets if you haven’t already.

Do share this post if you like.

Related Posts