Alex Adamcik
Alex Adamcik

Reputation: 1

Finding the average in a partially filled array

The Idea is to create a method that is static that will calculate the average salary for a partially-filled array. Assume that numEmployees holds the number of elements in the array that have valid data. numEmployees is passed to the method.

 public static double getAverage(double[ ] numEmployees)
{
double total = 0;  
 double average;
for (int i = 0; i < numEmployees.length; i++)
total += numEmployees[i];

average = total / numEmployees.length;

return average;
}

Do I need to add a part in the method that counts the array that are filled? like:

 int count=0;
 int p=0;
 if (numEmployees[p]>0)
 {
 count++;
 p++;
 }

or should I add a part in my for loop inside the message and change my total to this:

for (int i = 0; i < numEmployees.length || numEmployees>0; i++)
 total += numEmployees[i];

Than farther down

 average = total / i;

Upvotes: 0

Views: 1732

Answers (1)

Steven
Steven

Reputation: 2477

public static double getAverage(double[] numEmployees)
{
    double total = 0; 
    double count = 0; 
    for (int i = 0; i < numEmployees.length; i++)
        if (numEmployees[i] > 0) {
            total += numEmployees[i];
            count++;
        }

    return total / count;
}

Note that if there can be no more values after the first 0, it's also good to end the loop when one is detected. What i wrote here looks for any value greater than 0, no matter where the 0's occur.

Upvotes: 5

Related Questions