C# How To Find the Average of an Array
Find Array Average
Add all the elements, and divide the sum by the number of elements:
Example
int[] numbers = {10, 20, 30, 45};
int sum = 0;
foreach (int num in numbers)
{
sum += num;
}
double average = (double)sum / numbers.Length;
Console.WriteLine("Average: " + average);
The Average() method from the System.Linq namespace does the same in one line:
Example
int[] numbers = {10, 20, 30, 45};
Console.WriteLine("Average: " + numbers.Average());
Explanation:(double)sum turns the sum into a double before the division, so the decimals are kept. Without it, 105 / 4 would give 26, not 26.25.