find the sum of all elements in an array in csharp

To find the sum of all elements in an array in C#, you can use a loop to iterate over each element and add them up. Here is an example:

main.cs
int[] nums = { 1, 2, 3, 4, 5 };
int sum = 0;

for (int i = 0; i < nums.Length; i++)
{
    sum += nums[i];
}

Console.WriteLine("Sum of array elements: " + sum);
161 chars
10 lines

In this example, we first declare an array called nums with some values. We also declare a variable sum to hold the total sum.

We then use a for loop to iterate over each element in the array. Inside the loop, we add each element to the sum variable using the += operator.

Finally, we output the total sum using Console.WriteLine(). The output in this case would be:

main.cs
Sum of array elements: 15
26 chars
2 lines

gistlibby LogSnag