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.
-
We created a C# console application.
-
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};
- We also declared a variable
sum
to store the total sum of all the array elements.
int sum = 0;
- 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];
}
-
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 writingsum = sum + array[i];
. -
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. -
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#.