Home Java Java-tips Data Arrays Mean - average

Ask Questions?

View Latest Questions

Advertisement


 
 

Mean - average
Posted on: July 26, 2006 at 12:00 AM
Computing the arithmetic average (mean) can be done in one pass over all the array elements.

Java Notes

Mean - average

Computing the arithmetic average (mean) can be done in one pass over all the array elements.

//================================================= mean
public static double mean(double[] p) {
    double sum = 0;  // sum of all the elements
    for (int i=0; i<p.length; i++) {
        sum += p[i];
    }
    return sum / p.length;
}//end method mean

Question: What will this method do if it is passed an array with no elements in it, ie p.length == 0 ?

Why is this public?

This method is declared public because it is a general method that might be useful to someone else. It could be just as easily be declared private or simply have the default "package" permission.

Why is this static?

See Static methods for a discussion of why methods that only use their parameters and local variables should be declared static.

Copyleft 2003 Fred Swartz MIT License
Advertisement


DMCA.com