C# How To Calculate the Sum of Array Elements
Sum of Array Elements
Loop through the array, and add each element to a sum:
Example
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
foreach (int num in numbers)
{
sum += num;
}
Console.WriteLine("Sum: " + sum);
You can also use the Sum() method from the System.Linq namespace:
Example
int[] numbers = {10, 20, 30, 40, 50};
Console.WriteLine("Sum: " + numbers.Sum());
Explanation:sum starts at 0, and the loop adds each number to it. 10 + 20 + 30 + 40 + 50 is 150.Sum() does the same work for you, in one line.
Related Pages
C# Loop Through Arrays Tutorial