Sum all values in an array
Calculate the sum of all integers in an array without using LINQ.
Course progress
Problem 12 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
numbers = [4, -2, 7, 1]
Expected output
10
What is happening?
Add the values in order: 4 + (-2) + 7 + 1 = 10.
Solution strategy
Build the right mental model
Start an accumulator at zero and add each value during one pass through the array. Use long for the running total to support sums outside the int range.
Core concepts
arrays · accumulator
Complexity
Time O(n), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for sum-array-values
using System;
class Program
{
static long Sum(int[] numbers)
{
long total = 0;
foreach (int number in numbers) total += number;
return total;
}
static void Main()
{
Console.WriteLine(Sum(new[] { 4, -2, 7, 1 }));
}
}Knowledge check
Questions students often ask
What is the main idea behind sum all values in an array?
Start an accumulator at zero and add each value during one pass through the array. Use long for the running total to support sums outside the int range.
What is the time and space complexity of this solution?
Time O(n), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.