03. Calculate the Sum of Array Elements
Compute the sum of all numerical values in a given array.
How It Works & Algorithmic Design
This utilizes the Accumulator Pattern:
- State Initialization: Declare an accumulator variable
total = 0. Zero acts as the additive identity element ($x + 0 = x$). - Iteration: Walk through the elements one by one.
- Accumulation: Add each element's value to
totalusing the addition assignment operator (total += element). - Return: Once the loop completes, return
total.
Why This Approach Works Best
It performs a single pass over the array with constant extra space ($O(1)$ memory). For large arrays, integer overflow should be considered depending on the language (e.g., using 64-bit integers like long in Java when working with large numbers).
Example Walkthrough
Input:
[1, 2, 3, 4, 5]Sequential numbers from 1 to 5.
Step-by-Step Calculation:
0 + 1 = 1 | 1 + 2 = 3 | 3 + 3 = 6 | 6 + 4 = 10 | 10 + 5 = 15Accumulates values step by step.
Output:
15Total sum of all elements.
Answer: Calculate total sum
function sum(arr) {
let total = 0;
for (const value of arr) {
total += value;
}
return total;
}💡 Iterate through the array and accumulate values into a tracking variable.
Key Takeaways
- Initialize accumulators with the identity element (
0for sum,1for product). - Time complexity is $O(n)$ as every element is visited once.
- In languages like Java or C++, use
longto prevent overflow when dealing with large numbers.