How to calculate average of all numbers of array in Java? Example

In the last article, I teach you how to calculate the sum of all numbers in a given array, and in this article, we'll go one more step. This time, you need to write a program to calculate the average of all numbers from a given array, for example, you will be passed salaries of Java developers in different states in the USA and you need to calculate the average salary of Java developers in the USA. The example of the average salaries of Java developers is more interesting because everybody wants to know how much Java developers make, isn't it? 

Anyway, coming back to the requirement of the program, The array will contain integers, which can be both positive and negative, so you must handle them. Your program should also be robust e.g. it should not break if you pass an empty array or null. In these cases either you can throw IllegalArgumentException as returning any other number will be ambiguous.

For example, if you return zero then it could also be a possible average, so I won't suggest you return default values like zero or Integer.MIN_VALUE etc. Instead, throwing IllegalArgumentException and printing the input array would be a clear indication that a wrong input has been passed to this method.

Similar to the previous exercise this is also a simple one if you know how to get numbers from an array, how to get the length of an array, and how to iterate over an array in Java, as shown here. Actually, there are many ways to loop over an array in Java, like you can use the classical for loop, or while loop, or enhanced for loop from Java 1.5.

The easiest way is by using enhanced for a loop because you don't need to keep track of array indices, so there are fewer chances of error. It also looks clean on code and much more readable than classical for a loop.

In order to calculate the average of all numbers, you first need to calculate the sum of all elements, which you can do by following our last example. Once you have the sum just divide it by the total number of elements in the array, which is nothing but the length of the array. The result is the average of all numbers in the given array.




Java Program to calculate an average of all numbers in an array

Here is our complete Java program to find the average of all integers in the given array. Similar to the previous example, I have used Scanner to take input from the user, as shown here. Since it's not possible to directly input an array from the command prompt, you have to take individual elements and create an array from it as shown here

Once you got the required integer array, just pass it to the average(int[] input) method, it returns a float value, which is the average of all numbers in the given array.

In this method, we first calculate the sum of all elements and divide the total sum by the length of the array to get the average. There is a trick here, if you declare sum as an int variable then your average will not be always accurate because it will become an integer division and the result of integer division will always be an integer and not a floating-point value.  

How to calculate average of array in Java


Just remember to declare the sum as a float variable to avoid that logical mistake. You can also join these free Java beginner courses from Udemy and Coursera to learn more about integer and floating-point divisions in Java.

import java.util.Scanner;

/*
 * Java Program to calculate average of numbers in array
 * input : [1, 2, 3, 4, 5]
 * output: 3.0
 */

public class ArrayAverageProblem {

  public static void main(String[] args) {

  System.out
  .println("Welcome to Java Prorgram to calculate average of numbers");
  System.out.println("Please enter length of the array?");

  Scanner scnr = new Scanner(System.in);
  int length = scnr.nextInt();
  int[] input = new int[length];

  System.out.println("Please enter numbers ");

  for (int i = 0; i < length; i++) {
  input[i] = scnr.nextInt();
  }

  float average = average(input);

  System.out.println("Average of all numbers in array is " + average);
  scnr.close();
  }

  /**
  * Java method to calculate average of all numbers of array
  * 
  * @param input
  * @return average of all numbers in array
  */
  public static float average(int[] input) {
  float sum = 0f;
  for (int number : input) {
  sum = sum + number;
  }
  return sum / input.length;
  }

}

Output
Welcome to Java Program to calculate average of numbers
Please enter the length of the array?
5
Please enter numbers
1
2
3
4
5
Average of all numbers in array is 3.0

You can see here average is correctly calculated as 3.0 because the total sum is 15 and the total number of elements is 5, but if you change the sum as int sum = 0; instead of float sum = 0f; and enter the following values you will get incorrect answer e.g.

Please enter the length of the array?
2
Please enter numbers
4
5
The average of all numbers in the array is 4.0


This happens because 9/2 becomes an integer division and the result of integer division is always an integer value, so 4.5 is cast into int and it becomes 4. 

When you declare sum as float value then it becomes a floating-point calculation and the denominator will be promoted to float before division hence you will get the correct average which would be 4.5. Please see Java: A Beginner's Guide by Herbert Schildt to learn more about integer and floating-point calculation in Java. 

How to calculate average of all numbers in array?


That's all about how to calculate the average of all numbers of an array. This program might seem very simple to you if you know how to calculate average but it teaches you a very important concept in Java i.e. difference between integer and floating-point calculation. 

I have seen many programmers even experience one make that difference by declaring the sum as an int variable and testing with one set of values for which the method returns the correct average.

This also teaches you another lesson on Unit testing e.g. never believe your method is working correctly by testing with one set of values, you should always test with multiple values e.g. positive and negative values, boundary condition, null, zero, and empty array. 

You can consider writing those unit tests as a task for you. If you don't know how to write Junit test cases in Java then please refer to JUnit in Action or Test-Driven, a TDD and acceptance TDD guide for Java developers.  Any time invested in learning to write a unit test and actually writing those tests is worth their money.


Other Java Programming exercises for Beginners
  • How to reverse an array in place in Java? (solution)
  • How to remove duplicate elements from the array in Java? (solution)
  • How to implement binary search in Java? (solution)
  • How to check if a String contains duplicate characters in Java? (solution)
  • How to print Fibonacci series in Java (solution)
  • How to check if the given string is palindrome or not in Java? (solution)
  • How to reverse a String in place in Java? (solution)
  • How to find all permutations of a given String in Java? (solution)
  • How to find the highest occurring word from a given file in Java? (solution)
  • How to check if two given Strings are Anagram in Java? (solution)
  • How to implement Linear Search in Java? (solution)
  • How to find if given Integer is Palindrome in Java? (solution)
  • How to count vowels and consonants in a given String in Java? (solution)
  • How to check if two rectangles intersect with each other in Java? (solution)
  • How to remove duplicate characters from String in Java? (solution)
  • How to check if a year is a leap year in Java? (solution)
  • How to reverse words in a given String in Java? (solution)
  • How to calculate the Area of Triangle in Java? (program)
  • How to check if the given number is prime in Java (solution)
  • How to calculate the square root of a given number in Java? (solution)


And, lastly, what is your favorite Java programming exercise? Palindrom, Prime Number, Fibonacci series, Binary Search, or this one?  Do let me know in comments. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.