Problem overview
This version computes statistics for a whole class. The scores are in a List<int> named scores: 92, 78, 85, 67, 74, 88, 91 and 58. The program prints three lines: the highest score, the lowest score and the average, with the average rounded down to a whole number.
Highest: 92
Lowest: 58
Average: 79
The eight scores add up to 633, and 633 divided by 8 is 79.125, so the integer average is 79.
Approach: two library calls and one running total
The highest and lowest values are easy to get from the library. scores.Max() returns the largest element and scores.Min() the smallest. Both are LINQ methods that live in the System.Linq namespace, so a file needs using System.Linq; to call them on a list. They scan the whole list once, so you do not need to write a loop to find the extremes.
The average needs the sum. Create an int named total that starts at 0, then add every score to it with a foreach loop. A running total always starts at zero, before any score has been counted. Then divide the total by the number of scores. For a List<T> the number of elements is the Count property.
Both operands of the division are int, so C# truncates the result: 633 / 8 gives 79, and the fraction .125 is dropped. For a list of non-negative scores, truncation means rounding down, which is what the lesson asks for.
Step by step
- Find the highest score with
int highest = scores.Max();. One call, no loop. - Find the lowest with
int lowest = scores.Min();, the mirror of the first call. - Create the running total.
int total = 0;will hold the sum of all the scores. - Add every score.
foreach (int s in scores) total += s;visits each score in turn, 92, then 78, and so on. The loop body is a single statement, so it fits on one line without braces. - Compute the average as
total / scores.Count. Both areint, so the part after the point is dropped: the result is 79, not 79.125. - Print three lines with
Console.WriteLine:"Highest: " + highest, then"Lowest: " + lowest, then"Average: " + average, in that order.
The solution in C#
List<int> scores = new List<int> { 92, 78, 85, 67, 74, 88, 91, 58 };
int highest = scores.Max();
int lowest = scores.Min();
int total = 0;
foreach (int s in scores) total += s;
int average = total / scores.Count;
Console.WriteLine("Highest: " + highest);
Console.WriteLine("Lowest: " + lowest);
Console.WriteLine("Average: " + average);
Details worth knowing:
CountorLength. AList<T>hasCount, an array hasLength. Mixing them up is a compile error.- The collection initializer.
new List<int> { 92, 78, ... }creates the list and adds the values in one expression. Unlike an array, the list can grow later withAdd. - LINQ can do more.
scores.Sum()returns 633 here, andscores.Average()returns adouble, 79.125 for this data. The lesson uses an explicit loop for the total so that the running-total pattern is clear, and an integer division for the average. - Shorthand in the loop.
total += sis the same astotal = total + s.
Edge cases and common mistakes
- An empty list.
Max()andMin()on an empty list ofintthrow anInvalidOperationExceptionwith the message "Sequence contains no elements". The divisiontotal / scores.Countwould fail too, with aDivideByZeroException, since the count is 0. The lesson's data always has scores. - A missing
using. WithoutSystem.Linqin scope,scores.Max()does not compile, because aList<int>has noMaxmethod of its own. - Not starting the total at 0. A
totalthat starts at another value shifts the average. In C# a local variable must also be assigned before+=reads it, so declaring it without a value is a compile error. - Dividing by the wrong count. Use
scores.Count, not a number typed by hand, so the code keeps working when the list changes. - Expecting rounding to nearest. Integer division truncates. The scores 80, 80, 81, 81 and 81 add up to 403, and 403 / 5 is 80.6 exactly, but the program prints 80.
Testing
- The starting list prints
Highest: 92,Lowest: 58andAverage: 79. - The list 90, 91 prints
Highest: 91,Lowest: 90andAverage: 90, because 181 / 2 is 90.5, cut down to 90. - The one-element list 75 prints 75 on all three lines.
- The list 80, 80, 81, 81, 81 prints
Highest: 81,Lowest: 80andAverage: 80.
