Array Sum
Number Arrays
Coding Tutorial
Programming Guide
Summation Algorithms

How to find the sum of an array of numbers

Codemia Knowledge Hub ·

Introduction

Summing an array of numbers is one of the most fundamental operations in programming. Every language provides at least one built-in way to do it, and most offer several options ranging from simple loops to functional-style reduce operations. The choice depends on readability, performance, and whether you need to handle edge cases like empty arrays, floating-point precision, or very large numbers. This article covers the standard approaches in JavaScript, Python, Java, C#, Go, and Rust.

JavaScript

javascript
1const numbers = [1, 2, 3, 4, 5];
2
3// reduce (most common)
4const sum1 = numbers.reduce((acc, n) => acc + n, 0);
5console.log(sum1);  // 15
6
7// for...of loop
8let sum2 = 0;
9for (const n of numbers) {
10    sum2 += n;
11}
12
13// forEach
14let sum3 = 0;
15numbers.forEach(n => sum3 += n);
16
17// Edge case: empty array
18[].reduce((a, b) => a + b, 0);  // 0 (initial value prevents error)
19[].reduce((a, b) => a + b);     // TypeError: Reduce of empty array with no initial value

Always provide an initial value (0) to reduce(). Without it, an empty array throws a TypeError.

Python

python
1numbers = [1, 2, 3, 4, 5]
2
3# Built-in sum() — preferred
4total = sum(numbers)  # 15
5
6# With a start value
7total_plus_10 = sum(numbers, 10)  # 25
8
9# functools.reduce
10from functools import reduce
11total = reduce(lambda a, b: a + b, numbers)  # 15
12
13# NumPy for large arrays (much faster)
14import numpy as np
15arr = np.array([1, 2, 3, 4, 5])
16total = np.sum(arr)  # 15
17
18# math.fsum for floating-point precision
19import math
20floats = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
21print(sum(floats))        # 0.9999999999999999
22print(math.fsum(floats))  # 1.0

Python's sum() is the idiomatic choice. Use math.fsum() when floating-point precision matters and numpy.sum() for large numerical arrays.

Java

java
1int[] numbers = {1, 2, 3, 4, 5};
2
3// Traditional for loop
4int sum = 0;
5for (int n : numbers) {
6    sum += n;
7}
8System.out.println(sum);  // 15
9
10// Streams (Java 8+)
11int streamSum = java.util.Arrays.stream(numbers).sum();
12System.out.println(streamSum);  // 15
13
14// With List<Integer>
15List<Integer> list = List.of(1, 2, 3, 4, 5);
16int listSum = list.stream().mapToInt(Integer::intValue).sum();
17
18// Long sum to avoid integer overflow
19long longSum = java.util.Arrays.stream(numbers).asLongStream().sum();

Arrays.stream(arr).sum() is the clean modern approach. Use .asLongStream() if the sum could exceed Integer.MAX_VALUE (approximately 2.1 billion).

C#

csharp
1int[] numbers = { 1, 2, 3, 4, 5 };
2
3// LINQ Sum()
4int sum = numbers.Sum();  // 15
5
6// Aggregate (like reduce)
7int sum2 = numbers.Aggregate(0, (acc, n) => acc + n);
8
9// For loop
10int sum3 = 0;
11foreach (var n in numbers) sum3 += n;
12
13// Span<T> for performance-critical code
14ReadOnlySpan<int> span = numbers;
15int sum4 = 0;
16foreach (var n in span) sum4 += n;

LINQ's .Sum() is the standard approach in C#. For high-performance scenarios, a foreach loop over a Span<T> avoids the LINQ overhead.

Go

go
1package main
2
3import "fmt"
4
5func sum(numbers []int) int {
6    total := 0
7    for _, n := range numbers {
8        total += n
9    }
10    return total
11}
12
13func main() {
14    numbers := []int{1, 2, 3, 4, 5}
15    fmt.Println(sum(numbers))  // 15
16}

Go does not have a built-in sum() function or a reduce method. A for range loop is the standard and only approach.

Rust

rust
1fn main() {
2    let numbers = vec![1, 2, 3, 4, 5];
3
4    // Iterator sum (preferred)
5    let total: i32 = numbers.iter().sum();
6    println!("{}", total);  // 15
7
8    // fold (like reduce)
9    let total2: i32 = numbers.iter().fold(0, |acc, &x| acc + x);
10    println!("{}", total2);  // 15
11}

Rust's .iter().sum() requires a type annotation because Rust needs to know which numeric type to use for accumulation.

TypeScript with Type Safety

typescript
1function sum(numbers: number[]): number {
2    return numbers.reduce((acc, n) => acc + n, 0);
3}
4
5// Generic for different number-like types
6function sumBigInts(numbers: bigint[]): bigint {
7    return numbers.reduce((acc, n) => acc + n, 0n);
8}
9
10console.log(sum([1, 2, 3, 4, 5]));  // 15
11console.log(sumBigInts([1n, 2n, 3n]));  // 6n

Performance Comparison (JavaScript)

javascript
1const arr = Array.from({ length: 1_000_000 }, (_, i) => i);
2
3// for loop — fastest
4console.time('for');
5let s1 = 0;
6for (let i = 0; i < arr.length; i++) s1 += arr[i];
7console.timeEnd('for');  // ~2ms
8
9// reduce — slightly slower
10console.time('reduce');
11const s2 = arr.reduce((a, b) => a + b, 0);
12console.timeEnd('reduce');  // ~5ms
13
14// forEach — similar to reduce
15console.time('forEach');
16let s3 = 0;
17arr.forEach(n => s3 += n);
18console.timeEnd('forEach');  // ~5ms

For most applications, the performance difference is negligible. Use reduce for readability. Use a for loop in performance-critical hot paths.

Common Pitfalls

  • Empty array without initial value in reduce: [].reduce((a, b) => a + b) throws an error in JavaScript. Always provide 0 as the initial value to handle empty arrays gracefully.
  • Integer overflow: In Java (int), C (int), and similar typed languages, summing large arrays can overflow. Use long or BigInteger when the sum could exceed the integer range.
  • Floating-point precision: sum([0.1, 0.2, 0.3]) may not equal 0.6 exactly due to IEEE 754 representation. Use math.fsum() in Python or Kahan summation in other languages for precise floating-point sums.
  • Shadowing Python's built-in sum: Naming a variable sum (sum = 0) overwrites the built-in sum() function for the rest of the scope. Use total instead.
  • NaN propagation: In JavaScript, if the array contains NaN, undefined, or non-numeric values, the sum becomes NaN. Filter or validate the array before summing: arr.filter(Number.isFinite).reduce(...).

Summary

  • Python: sum(array) — simplest built-in, use math.fsum for float precision
  • JavaScript: array.reduce((a, b) => a + b, 0) — always include the initial value 0
  • Java: Arrays.stream(arr).sum() — use .asLongStream() for large sums
  • C#: array.Sum() via LINQ
  • Go: for range loop (no built-in sum function)
  • Rust: array.iter().sum() with type annotation
  • For all languages, handle empty arrays and integer overflow as edge cases

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Basis Lab
This one is answered in full over here

“What does the sigma notation with i=1 underneath and n on top actually tell me to add?” is the same question written out properly on Basis Lab, with the course it belongs to beside it. Basis Lab is a separate product from the same team and both are free to read.

Read the answer
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms