Home Java Beginners Average of Array

 
 

Share on Google+Share on Google+

Average of Array

Advertisement
In this section, we will learn how to get an average of array.

Average of Array

     

In this section, we will learn how to get an average of array. For this, first of all we have to define a class name "ArrayAverage" that has double type array to contain some values. Now we take a double type data that calculates the average of array (result/nums.length). And finally it will display the result on the command prompt with message by using the System.out.println().

 

Here is the code of this program

 

 

public class ArrayAverage{
  public static void main(String[] args) {
  double nums[]={1.0,2.3,3.4,4.5,40.5};
  double result=0.0;
  int i=0;
  for(i=0; i < nums.length; i++){
  result=result + nums[i];
  }
  System.out.println("Average is =" + result/nums.length);
  }
}

Download this Example

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 5, 2007

Related Tutorials

Discuss: Average of Array   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:3
Isaiah
January 27, 2012
Great, one note though.

If you use a integer array you need to cast nums.length to a double before you calculate it. result = sum / (double) nums.length
rommel
February 23, 2012
programing

hi. am rommel ilagan
rainbow
November 3, 2012
need help with java

create java program take n values (double) from user,store in array and use overload method to calculate average based on : 1- method take no parameter and calculate average for all values 2- method takes 2 double parameter (m,n) and calculate avg value of all numbers between range m to n 3- method takes string parameter x if x="pos" then calculate positive values,if x="fact" then calculate average values of factorial values of all positive numbers use method to print all n values and average values as output
DMCA.com