How To Find Sum Of An Array Of Numbers In C#

Introduction

There are a lot of ways to find the sum of an array of numbers. But in C# we mainly have four ways to do this. System.Linq namespace contains two methods to find the sum of an array of numbers. Two other ways are using for loop and Array.ForEach() method.

Let's explore all four ways to find the sum of an array of numbers.

Using Enumerable.Sum() method

The enumerable class provides a set of static methods for querying objects that implements IEnumerable<T>. To know more about Enumerable class please visit the official site. In this, we will use Sum() method to find the sum of an array of numbers as given below.

using System;
using System.Linq;
public class ArraySum {
    public static void Main() {
        int[] arr = {
            10,
            20,
            30,
            10
        };
        int sum = arr.Sum();
        Console.WriteLine(sum);
        Console.ReadLine();
    }
}

Output

70

Using Enumerable.Aggregate() method

This is the second method in the System.Linq namespace to find the sum of an array of numbers. In this, we will use the Aggregate() method to find the sum as given below.

using System;
using System.Linq;
public class SumArray {
    public static void Main() {
        int arr[] = {
            10,
            20,
            30,
            10
        };
        int sum = arr.Aggregate((result, next) => result + next);
        Console.WriteLine(sum);
        Console.ReadLine();
    }
}

Output

70

Using Array.ForEach() method

Using this method, we can also find the sum of an array of numbers.

Using System;
public class SumArray {
    public static void Main() {
        int[] arr = {
            10,
            20,
            30,
            10
        };
        int sum = 0;
        Array.ForEach(arr, i => sum = sum + i);
        Console.WriteLine(sum);
        Console.ReadLine();
    }
}

Output

70

Using for loop

Using for loop is widely used to find the sum of an array of numbers. In all the programming languages we can use for loop to find the sum.

using System;
public class SumArray() {
    public static void Main() {
        int[] arr = {
            10,
            20,
            30,
            10
        };
        int sum = 0;
        for (int i = 0; i < arr.Length; i++) {
            sum = sum + arr[i];
        }
        Console.WriteLine(sum);
    }
}

Output

70

Conclusion

Using language-specific methods to accomplish any task is the best way to do that. Because each programing language has its own methods and way to find the sum of an array of numbers.

Thank you and Stay Tuned for More   

More articles from my account