Sum up an array of integers in C#
This post will discuss how to sum up an array of integers in C#.
1. Using Enumerable.Sum Method
Starting with .NET 3.5, you can use the Enumerable.Sum method to compute the sum of a sequence of numeric values. It is available in System.Linq namespace and can be used as follows:
|
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[] arr = { 5, 3, 7, -1, 2}; int sum = arr.Sum(); Console.WriteLine("Sum is " + sum); } } |
Output:
Sum is 16
The sum() method is overloaded for Decimal, Double, Int32, and Int64 values. For other numeric data types like Short and Long, do as follows:
|
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() { short[] arr = { 5, 3, 7, -1, 2 }; int sum = arr.Select(x => (int)x).Sum(); Console.WriteLine("Sum is " + sum); } } |
Output:
Sum is 16
2. Using Enumerable.Aggregate Method
Another efficient way of accomplishing this would be with the Aggregate() method by LINQ, which applies an accumulator function over a sequence. Here’s an example of its usage:
|
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[] arr = { 5, 3, 7, -1, 2}; int sum = arr.Aggregate((x, y) => x + y); Console.WriteLine("Sum is " + sum); } } |
Output:
Sum is 16
3. Using ForEach method
If you don’t prefer LINQ or do not use .NET 3.5 or above, you can use a foreach loop to compute the sum of an array of integers.
|
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[] arr = { 5, 3, 7, -1, 2 }; int sum = 0; foreach (var i in arr) { sum += i; } Console.WriteLine("Sum is " + sum); } } |
Output:
Sum is 16
Here’s an equivalent version using the Array.ForEach method.
|
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[] arr = { 5, 3, 7, -1, 2}; int sum = 0; Array.ForEach(arr, delegate(int i) { sum += i; }); Console.WriteLine("Sum is " + sum); } } |
Output:
Sum is 16
That’s all about summing up an array of integers 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 :)