Calculate sum of all elements of an array in C#
This post will discuss how to calculate the sum of all elements in an integer array in C#.
1. Using Enumerable.Sum() method
We can make use of the built-in numeric aggregation method Sum() from the System.Linq namespace to compute the sum of numeric values in a sequence. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.Linq; public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; int sum = array.Sum(); Console.WriteLine(sum); } } |
2. Using Array.ForEach() method
Using the Array.ForEach() method, we can perform the addition operation on each element of the specified array. The following example demonstrates this by finding the total sum of all the array elements using Array.ForEach():
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
using System; public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; int sum = 0; Array.ForEach(array, i => sum += i); Console.WriteLine(sum); } } |
3. Using foreach loop
We can also loop through the array elements using the foreach statement and compute the sum on the fly. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
using System; public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; int sum = 0; foreach (int item in array) { sum += item; } Console.WriteLine(sum); } } |
4. Using Enumerable.Aggregate() method
Finally, one can use the Enumerable.Aggregate() method in System.Linq Namespace, which applies an accumulator function on each element of a sequence.
The following code example demonstrates how to use Aggregate to perform addition.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using System; using System.Linq; public class Example { public static void Main() { int[] array = { 1, 2, 3, 4, 5 }; int sum = array.Aggregate((total, next) => total + next); Console.WriteLine(sum); } } |
That’s all about calculating the sum of all elements of an array in C#.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)