Java Program to calculate Average of Integer Array

average of number java

In this tutorial, we are going to learn a writing java program to find the average of given numbers. In this program basically, we will not take any user input. We have an integer array so we will iterate the integer array and then calculate the average number.

Problem Statement

For any given sequence of predefined numbers, we have to calculate the average of the numbers (none of the values are taken from the user).

For example

Case1: If the predefined sequence 1,2,3,4,5,6,7,8,9.
The output should be 5.
Case2: If the predefined sequence 11,22,33,44,55,66,77,88,99.
The output should be 55.

Our Logic to calculate the Average of Array

  • Our program will declare the variable sum =0, i=0 and also the array is predefined at the beginning.
  • Then. Our program will calculate the sum of all the numbers using ‘while loop’.
  • Finally, the Calculated sum is then divided by the number of elements present in the array (or length of the array) and print the result as the output.

What is the average of the numbers?

Average also called the arithmetic mean, is calculated by adding a group or collection of numbers and then dividing that sum by the number of elements of the same group or collection.

Algorithm to calculate average of the numbers

Step 1: Start

Step 2: float sum =0, int i=0.

Step 3: int [] arr = {1,2,3,4,5}

Step 4: while (I < arr.length) { sum = sum+arr[i]; }

Step 5: assign a variable, avg as float average = sum/arr.length;

Step 6: print average

Step 7: Stop

Java Program to calculate the Average of a given integer array

Output 1

Explanation

In this example, the predefined array is {1, 2, 3, 4, 5}. Where the size of array is 5 so the average will be

Average = (1+2+3+4+5)/ 5

The output generated is 3.0.

Output 2

Explanation

In this example, the predefined array is {0, 9, 34, 47, 100}. Where the size of the array is 5 so the average will be

Average = ( 0+9+34+47+100 )/ 6

The output generated is 38.0.