Java Program to Calculate Average Using Arrays
A quick and practical guide to find and to calculate the average of numbers in array using java language.
1. Overview
In this article, you’ll learnhow to calculate the average of numbers using arrays.
You should know the basic concepts of a java programming language such asArrays andforEach loops.
We’ll see the two programs on this. The first one is toiterate the arrays using for each loop and find the average.
In the second approach, you will read array values from the user.
Let us jump into the example programs.
2. Example 1 to calculate the average using arrays
First, create an array with values and run. thefor loop to find the sum of all the elements of the array.
Finally,divide the sum with the length of the array to get the average of numbers.
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | packagecom.javaprogramto.programs.arrays.average;publicclassArrayAverage { publicstaticvoidmain(String[] args) { // create an array int[] array = {1,2,3,4,5,6,7,8,9,10,11,12}; // getting array length intlength = array.length; // default sium value. intsum =0; // sum of all values in array using for loop for(inti =0; i < array.length; i++) { sum += array[i]; } doubleaverage = sum / length; System.out.println("Average of array : "+average); }} |
Output:
1 | Average of array :6.0 |
3. Example 2 to find the average from user inputted numbers
Next, let us read the input array numbers from the user using theScanner class.
Scanner Example to add two numbers
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | importjava.util.Scanner;publicclassArrayAverageUserInput { publicstaticvoidmain(String[] args) { // reading the array size. Scanner s =newScanner(System.in); System.out.println("Enter array size: "); intsize = s.nextInt(); // create an array int[] array =newint[size]; // reading values from user keyboard System.out.println("Enter array values : "); for(inti =0; i < size; i++) { intvalue = s.nextInt(); array[i] = value; } // getting array length intlength = array.length; // default sium value. intsum =0; // sum of all values in array using for loop for(inti =0; i < array.length; i++) { sum += array[i]; } doubleaverage = sum / length; System.out.println("Average of array : "+ average); }} |
Output:
1 2 3 4 5 6 7 8 9 | Enter array size:5Enter array values : 1223344556Average of array :34.0 |
4. Conclusion
In this article, you’ve seenhow to calculate the average number in an array.
All examples shown are inGitHub.
Published on Java Code Geeks with permission by Venkatesh Nukala, partner at ourJCG program. See the original article here:Java Program to Calculate Average Using Arrays Opinions expressed by Java Code Geeks contributors are their own. |

Thank you!
We will contact you soon.



