The problem was pretty straightforward and used two simple algorithms from our examples; the one for computing the sum, and the one for counting matches. The array for the problem wasn't provided, but you can easily write a method around it without actually having it, since she gave us the name and type of the array. The code for my solution is this:
public class Tests
{
private double[] grades;
public int belowAverage() // Creates method for finding scores below the mean
{
double total = 0;
for (double element1 : grades) // Computes total of array 'grades'
{
total=total + element1;
}
double mean = total / grades.length; //Uses total and the length of the array to computer the mean
int matches = 0;
for (double element2 : grades) //Uses mean to compute number of grades that are below the mean and
{ // increases matches for each one that is.
if (element2 < mean) {matches++;}
}
return matches; // Returns the number of matches.
}
}
Obviously the third line would change if you had the actual array. That was just kind of a placeholder. I tried to notate the code well enough to see where you get the total, then the mean, then compare each one to the mean to get matches that are less and increase your 'matches' variable for each match. I could have used the same 'element' variable for both loops since they're only used within the loops, but for clarity's sake in this example, I named them differently. I put all of these steps together in one method to solve this problem, but if I were going to write this sort of thing 'for real', I would assume it would probably need to calculate much more than just this small task (different averages, highest/lowest, etc.), so I would probably put each step in its own method so it could be used wherever you needed it.
Can someone comment on this and tell me if I could have done this in another way or an easier way? Maybe I could have used arrays.