Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum up an array of integers in C#

Tags:

arrays

c#

integer

People also ask

How do you find the sum of integers in C?

printf("Enter two integers: "); scanf("%d %d", &number1, &number2); Then, these two numbers are added using the + operator, and the result is stored in the sum variable. Finally, the printf() function is used to display the sum of numbers. printf("%d + %d = %d", number1, number2, sum);


Provided that you can use .NET 3.5 (or newer) and LINQ, try

int sum = arr.Sum();

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);

With LINQ:

arr.Sum()

An alternative also it to use the Aggregate() extension method.

var sum = arr.Aggregate((temp, x) => temp+x);

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.