Find Sum of Array in C#

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 2 Code Examples
Arrays

What you’ll learn

  • The accumulator pattern with sum += value.
  • Fixed-array and user-input variants in C#.
  • Handling empty arrays and negative values safely.
  • Why complexity is linear in the number of elements.

Overview

Array sum means adding every element exactly once. For {1, 2, 3, 4, 5}, the result is 15. This is the core accumulator pattern used in many interview problems.

Two C# programs

Fixed array sum and user-input array sum.

Live preview

Paste values like 10, -2, 7 and compute instantly.

Safe sum type

Use long when totals might exceed int.

Prerequisites

int[] arrays, foreach or for loops, and basic console I/O.

  • You know how to declare and initialize an array like int[] array = {1, 2, 3};.
  • You can read input with Console.ReadLine() and parse with int.TryParse.

Understanding the concept of sum of array

The sum of an array is obtained by adding up all the elements it contains — each value is counted exactly once.

For {1, 2, 3, 4, 5}, the sum is 1 + 2 + 3 + 4 + 5 = 15.

Accumulator pattern

Start with sum = 0, then for each element x do sum = sum + x. After the loop, sum holds the total.

Empty array

If there are no elements, the loop never runs and the sum stays 0.

Live preview

Enter integers separated by commas or spaces (for example: 1 2 3 or 1,2,3).

Negatives are allowed. Empty input is treated as no values.

Live result
Press “Compute sum”.

Algorithm

Goal: compute the sum of all elements in an array.

Initialize sum

Start with sum = 0 (or long sum = 0).

Traverse array

Visit each element once in a foreach or for loop.

Accumulate

Add each value into the running sum and return it.

📜 Pseudocode

Pseudocode
function arraySum(arr):
    sum = 0
    for each value in arr:
        sum = sum + value
    return sum
1

Sum of a fixed array

Reference program: sums {1, 2, 3, 4, 5} using a foreach loop.

c#
using System;

class Program
{
    static long FindSumOfArray(int[] arr)
    {
        long sum = 0;

        foreach (int element in arr)
            sum += element;

        return sum;
    }

    static void Main()
    {
        int[] array = { 1, 2, 3, 4, 5 };
        long sum = FindSumOfArray(array);

        Console.WriteLine($"Sum of the array elements: {sum}");
    }
}
2

Sum of user-input array

Reads n values from the console and accumulates the total — good practice for interview I/O.

c#
using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter number of elements: ");

        if (!int.TryParse(Console.ReadLine(), out int n) || n < 0)
        {
            Console.WriteLine("Invalid n.");
            return;
        }

        long sum = 0;

        for (int i = 0; i < n; i++)
        {
            Console.Write($"Enter element {i + 1}: ");

            if (!int.TryParse(Console.ReadLine(), out int x))
            {
                Console.WriteLine("Invalid element.");
                return;
            }

            sum += x;
        }

        Console.WriteLine($"Sum of the array elements: {sum}");
    }
}

Optimization and alternatives

One pass is optimal. A single traversal is already O(n) for an exact sum.

Use long. Safer totals when many large values are added.

LINQ (optional). array.Sum() works in .NET, but interviews often expect an explicit loop.

❓ FAQ

Initialize sum = 0 and loop through the array: sum += element (or sum += arr[i]).
Zero is the identity for addition, so it does not change the total.
Yes. The same loop works for positive, zero, and negative values.
Use long if values or count can be large to reduce overflow risk.
An empty array has sum 0 because no elements are added.
O(n), because each element is visited once.

🔄 Input / output examples

ArraySum
{1, 2, 3, 4, 5}15
{10, -2, 7}15
{} (empty)0

Edge cases and pitfalls

Summing is straightforward, but these cases are commonly asked in interviews.

Empty

Zero elements

No elements means the total stays 0.

Overflow

Large totals

Use long to reduce overflow risk when numbers are large.

Input

Validate parsing

Use int.TryParse and reject invalid tokens before summing.

⏱️ Time and space complexity

ApproachTimeExtra space
Single traversal sumO(n)O(1)

Summary

  • Pattern: initialize sum = 0, then add each value once.
  • Type: use long for safer totals.
  • Complexity: O(n) time and O(1) extra space.
Did you know?

Summing an array is the simplest form of the accumulator pattern: start with 0 and keep adding each element.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful