Java program to calculate the average of numbers in Java


An average of a set of numbers is their sum divided by their quantity. It can be defined as −

average = sum of all values / number of values

Here we shall learn how to programmatically calculate average.

Algorithm

1. Collect integer values in an array A of size N.
2. Add all values of A.
3. Divide the output of Step 2 with N.
4. Display the output of Step 3 as average.

Example

Live Demo

public class AverageOfNNumbers {
   public static void main(String args[]){
      int i,total;
      int a[] = {0,6,9,2,7};
      int n = 5;
      total = 0;

      for(i=0; i<n; i++) {
         total += a[i];
      }
      System.out.println("Average ::"+ total/(float)n);
   }
}

Output

Average ::4.8

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 13-Mar-2020

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements