Java Program Calculate Sum And Average Of Array

Sharing is healthy !!

In the following post you will learn java program calculate sum and average of array.

Here i am going to show you how to find the average of an array using Scanner class and without using Scanner class. So, let us get into code implementation,

Example: Java Program Calculate Sum And Average Of Array

public class AverageArray 
{
   public static void main(String[] args) 
   {
      int num[] = new int[]{30,12,14,24,19,89,128};
      int total = 0;

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

      double average = total / num.length;

      System.out.println("The total is : " + total);
      System.out.println("Java average of array : " + average);
   }
}

Output:

The total is : 316
Java average of array : 45.0


using scanner class

Here we are going to learn how to find the average of an array in java using scanner class,

Also Read – Java Array Copy Of Range Method

import java.util.Scanner;

public class AverageArray
{
   public static void main(String[] args) 
   {
      int a;
      int total = 0;
      double average;
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter number of integers in an array: ");
      a = sc.nextInt();
      int num[] = new int[a];
      System.out.println("Enter " + a + " integers.");

      for(int i = 0; i < a; i++)
      {
         num[i] = sc.nextInt();
         total = total + num[i];
      }
      System.out.println("Total: " + total);
      average = (double)total / a;
      System.out.println("Java average of array : " + average);
   }
}

Output:

Java Program Calculate Sum And Average Of Array


conclusion

That’s it guys. This all about java program calculate sum and average of array.

You have learnt how to find the average of an array with scanner class and without scanner class. I hope you enjoyed this post.

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

Do share this post if you like.

Sharing is healthy !!

You May Also Like