average of array in java

In this article we are going to find average of given array of numbers.

Example:-

Let’s a given array={2,4,6,8}, then the average of given array will be 5.

Steps:-

  • Take an array input from user.
  • create a variable sum and initialize it with 0.
  • Run a for loop to iterate the elements of array.
  • inside loop perform sum=sum+element or arra.
  • end of loop.
  • calculate average =sum/length of array.

Java code to find average of array:-

package gangforcode;

import java.util.Scanner;

public class Average {
 public static double average(int[] a) {
	 int sum =0;
	 for(int i=0;i<a.length;i++) {
		 sum =sum+ a[i];	 
	 }
	 double average=sum/a.length;
	 return average;
	 
 }
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the size of array");
		int n=sc.nextInt();
		
		int[]a=new int[n];
		System.out.println("Enter the element of array");
		for(int i=0;i<n;i++) {
			a[i]=sc.nextInt();
			
		}
		System.out.println(average(a));
	}

}

Output:-

average in array using java

Leave a Comment