Java Programs

Calculate Average of Integer Array

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

  1. Our program will declare the variable sum =0, i=0 and also the array is predefined at the beginning.
  2. Then. Our program will calculate the sum of all the numbers using ‘while loop’.
  3. 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

Program:

public class Main {
 
	public static void main(String[] args) {
		
	    float sum=0;
	    int i=0;
	    int[] arr = {1, 2, 3, 4, 5};
	    
	    while (i<arr.length) {
	        sum=sum+arr[i];
	       i++;
	    }
	    
	    float average = sum/arr.length;
	    System.out.println("Average of Array Integer is : "+average);
	}	
}

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 1:

Average of Array Integer is : 3.0

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.

Output 2:

Average of Array Integer is : 38.0

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs