How to sum up an array of integers in C#
How to sum up an array of integers in C#
Is there a better shorter way than iterating over the array?
int arr = new int 1, 2, 3 ;
int sum = 0;
for (int i = 0; i < arr.Length; i++)
sum += arr[i];
clarification:
Better primary means cleaner code but hints on performance improvement are also welcome. (Like already mentioned: splitting large arrays).
It's not like I was looking for killer performance improvement - I just wondered if this very kind of syntactic sugar wasn't already available: "There's String.Join - what the heck about int?".
People are so weird these days. "If there is not already a function for something, it is wrong". How much more simple can you get; iterate over the array, add them together. Yeesh.
– Ed S.
Mar 10 '10 at 18:30
Also, LOL at "cleaner code". What do you think the library's Array.Sum is doing when you call it?
– Ed S.
Mar 10 '10 at 18:30
@Ed: I'm not that daft to think that the less code i write, the faster it runs. But less code is more readable for sure and cleaner in that way.
– Filburt
Mar 10 '10 at 22:00
What's the matter folks? 3 hrs and still no exhaustive performance measurements comparing .Sum() vs. for() vs. foreach()?
– Filburt
Mar 10 '10 at 22:07
8 Answers
8
Provided that you can use C# 3.5 and LINQ, try
int sum = arr.Sum();
Thanks a lot - i assume you deserve the marker in this heartbeat finish. Especially for pointing out the C# 3.5 requirement.
– Filburt
Mar 10 '10 at 18:16
@Filburt / @Thomas: a minor correction: it's C# 3.0. The .NET version that provides the
Sum extension method is version 3.5.– Ahmad Mageed
Mar 10 '10 at 18:20
Sum
The identity lambda isn't necessary. Except to confuse the new guy on the team.
– Will
Mar 10 '10 at 18:23
It is worth noting that this will get raise an error
System.OverflowException if the result would be greater than you can fit in a signed 32 bit integer (i.e. (2^31) -1 or in english ~ 2.1 billion).– ChrisProsser
Mar 14 '15 at 20:15
System.OverflowException
Yes there is. With .NET 3.5:
int sum = arr.Sum();
Console.WriteLine(sum);
If you're not using .NET 3.5 you could do this:
int sum = 0;
Array.ForEach(arr, delegate(int i) sum += i; );
Console.WriteLine(sum);
+1 for the non-LINQ answer.
– Michael Itzoe
Mar 10 '10 at 18:12
Why such a convoluted pre 3.5 version? The
foreach loop is available in all versions of C#.– Jørn Schou-Rode
Mar 16 '10 at 9:37
foreach
@Jørn: the OP asked for a shorter approach. A
foreach just substitutes one line of code for another and isn't shorter. Apart from that a foreach is perfectly fine and is more readable.– Ahmad Mageed
Mar 16 '10 at 11:34
foreach
foreach
Point taken. Yet, the following saves 18 chars compared to your sample:
foreach (int i in arr) sum += i;– Jørn Schou-Rode
Mar 16 '10 at 11:44
foreach (int i in arr) sum += i;
With LINQ:
arr.Sum()
It depends on how you define better. If you want the code to look cleaner, you can use .Sum() as mentioned in other answers. If you want the operation to run quickly and you have a large array, you can make it parallel by breaking it into sub sums and then sum the results.
+1 Very good point on performance improvement but honestly my initial wish was to get rid off the iteration.
– Filburt
Mar 10 '10 at 18:21
(nobody tell Fil that he just pushed the iteration a couple levels down the stack)
– Will
Mar 10 '10 at 18:24
@Will: Dude - don't expect me to believe if i don't write the code magic will happen ;-)
– Filburt
Mar 10 '10 at 18:27
I suspect it would have to be a VERY large array before such a parallel optimization would make sense.
– Ian Mercer
Mar 10 '10 at 18:28
Yeah, since when did a for loop become bad practice?
– Ed S.
Mar 10 '10 at 18:31
If you don't prefer LINQ, it is better to use foreach loop to avoid out of index.
int arr = new int 1, 2, 3 ;
int sum = 0;
foreach (var item in arr)
sum += item;
Using foreach would be shorter code, but probably do exactly the same steps at runtime after JIT optimization recognizes the comparison to Length in the for-loop controlling expression.
In one of my apps I used :
public class ClassBlock
public int p;
public int Sum
get int s = 0; Array.ForEach(p, delegate (int i) s += i; ); return s;
Try this code:
using System;
namespace Array
class Program
static void Main()
int number = new int 5, 5, 6, 7;
int sum = 0;
for (int i = 0; i <number.Length; i++)
sum += number[i];
Console.WriteLine(sum);
The result is:
23
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Better in what way? Faster? Less written code?
– Fredrik Mörk
Mar 10 '10 at 18:13