Calculate Average Of An Array In Java

In the following post you will learn to calculate average of an array in java.

Here i am going to show you how to execute java program using Scanner class and without using Scanner class. So, let us get into code implementation,

Example: Calculate Average of an Array in Java without using scanner class

Also Read – Binary Search Program Java

public class Average_Array {

public static void main(String[] args) {

int num[] = new int[]{30,12,14,24,19,89,128};

int total = 0;

for(int a = 0;a < num.length;a++){
total = total + num[a];
}

double average = total / num.length;

System.out.println("Average value of an array is: " + average);
}
}

Output:

Average value of an array is: 45.0


Now using scanner class,

Example: Calculate Average of an Array in Java using scanner class

Also Read – Bitwise Addition Program

import java.util.Scanner;

public class Average_Array {

public static void main(String[] args) {

int a;
int total = 0;
double average;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of integers in an array: ");
a = sc.nextInt();
int num[] = new int[a];
System.out.println("Enter " + a + " integers.");
for(int i = 0;i < a;i++){
num[i] = sc.nextInt();
total = total + num[i];
}
System.out.println("Total: " + total);
average = (double)total / a;
System.out.println("Average value of an array is: " + average);
}
}

Output:

Calculate Average Of An Array In Java

About the author

admin

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *