Wednesday, September 22, 2010

Determining the average of the elements of an array of numbers

Algorithm
Given: an Array of numbers and the number of elements

1. declare a variable to hold the sum of all the elements and initialize it to 0.
2. declare a variable to hold the average of the elements
3. add the first element to sum
4. add the next element to sum
5. repeat from step 4 until all elements are added to sum
6. let average = sum divided by the number of elements
Note: The size of an array is returned when accessing the length attribute of an array in JAVA.

Implementation

double computeAverage(double[] array){
double sum=0;
double average = 0;
for (int x=0; x < array.length; x++)
sum = sum + array[x];
average = sum/array.length;
return average;
}

No comments:

Post a Comment