OneBite.Dev - Coding blog in a bite size

Find The Sum Of All Elements In An Array In C#

Code snippet for how to Find The Sum Of All Elements In An Array In C# with sample and detail explanation

In this article, we’re going to cover how to find the sum of all elements in an array using C#. This is a common problem that beginners might come across when they’re just starting to learn about the C# programming language.

Code snippet to find the sum of all elements in an array

class Program
{
   static void Main(string[] args)
   {
        int[] array = {1, 2, 3, 4, 5};
        int sum = 0;
        for (int i = 0; i < array.Length; i++)
        {
            sum += array[i];
        }
        Console.WriteLine("Sum = " + sum);
    }
}

Code Explanation for finding the sum of all elements in an array

Let’s break down the code piece by piece.

  1. We created a C# console application.

  2. In this application, we declared an array of int values. These are the numbers that we’ll be adding together.

int[] array = {1, 2, 3, 4, 5};
  1. We also declared a variable sum to store the total sum of all the array elements.
int sum = 0;
  1. We proceed to loop through each element in the array using a for loop. Every loop increases by 1 until the end of the array size. The index of the array starts at 0.
for (int i = 0; i < array.Length; i++)
{
    sum += array[i];
}
  1. For each iteration of the loop, we added the current element to the sum. That’s what sum += array[i]; does. This operation is the same as writing sum = sum + array[i];.

  2. Once the loop has gone through all the elements in the array, the sum of all the elements should be stored in the sum variable.

  3. Finally, we printed out the sum to the console using Console.WriteLine("Sum = " + sum). This will display the sum of all elements in the array.

That’s all! This simple way helps you to find the sum of all elements in an array in C#.

c-sharp