Sums, Averages, and Extremes in an Array
A sum
A hockey team's goals in its first seven games are stored in
goals.int[] goals = {3, 1, 4, 0, 2, 5, 2};
int total = 0;
for (int g : goals)
{
total += g;
}The variable
total starts at 0, outside the loop, since nothing has been added yet. Each pass adds one game's goals, and after the last pass total is 17. Declared inside the loop instead, it would start over at 0 on every pass and be out of scope after the loop.A count
The number of games with 3 or more goals takes an
if inside the loop.int bigGames = 0;
for (int g : goals)
{
if (g >= 3)
{
bigGames++;
}
}
The loop makes seven passes, but
bigGames++ runs only for the 3, the 4, and the 5. So the count is 3. A count adds 1 for each element that qualifies. Writing bigGames += g; would add up the goals in those games, 12, and answer a different question.An average
The team's average is its total divided by its number of games. Both
total and goals.length are int values, so total / goals.length is integer division, and 17 / 7 gives 2.Casting one operand keeps the fraction:
(double) total / goals.length is about 2.43. The expression (double) (total / goals.length) casts too late. The division has already produced 2, and the cast only changes it to 2.0.Maximum and minimum
int most = goals[0];
for (int i = 1; i < goals.length; i++)
{
if (goals[i] > most)
{
most = goals[i];
}
}
The variable
most starts with goals[0], so the loop's index starts at 1. It's replaced twice, by the 4 at index 2 and by the 5 at index 5, so it holds 5 when the loop finishes. The smallest value uses the same loop with < in place of >, and it ends with 0.Seeding
most with the first element works for any values, and seeding it with 0 doesn't. The team's goal differences in three losses were -2, -1, and -4. A maximum seeded with 0 is never replaced by any of them, so it reports 0, a value that isn't in the array. Seeded with the first element, it gives -1.Reading
goals[0] requires at least one element. A method that finds a maximum this way has a precondition that its array isn't empty, since otherwise there's no element to start from.