EN
C# / .NET - calculate average of array
0 points
In this article, we would like to show you how to calculate average of array in C#.
Quick solution:
xxxxxxxxxx
1
int[] numbers = { 1, 2, 3, 4 };
2
3
double average = numbers.Average();
4
5
Console.WriteLine(average); // Output: 2.5
or:
xxxxxxxxxx
1
int[] numbers = { 1, 2, 3, 4 };
2
3
int sum = 0;
4
5
if (numbers.Any())
6
foreach (int number in numbers)
7
sum += number;
8
9
double average = (double)sum / numbers.Length;
10
11
Console.WriteLine(average); // Output: 2.5
In this example, we use Average()
method from System.Linq
to caluclate average of the array.
xxxxxxxxxx
1
using System;
2
using System.Linq;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
int[] numbers = { 1, 2, 3, 4 };
9
10
double average = numbers.Average();
11
12
Console.WriteLine(average); // Output: 2.5
13
}
14
}
Output:
xxxxxxxxxx
1
2.5
In this example, we use foreach to sum all numbers in the List, then we divide the sum
by the number of elements.
xxxxxxxxxx
1
using System;
2
using System.Linq;
3
4
public class Program
5
{
6
public static void Main()
7
{
8
int[] numbers = { 1, 2, 3, 4 };
9
10
Console.WriteLine(average(numbers)); // Output: 2.5
11
}
12
13
private static double average(int[] array)
14
{
15
int sum = 0;
16
17
if (array.Any())
18
foreach (int number in array)
19
sum += number;
20
21
return (double)sum / array.Length;
22
}
23
}
Output:
xxxxxxxxxx
1
2.5