sumArray

Easy · Loops and Iterations · 4 test cases

Given an array of numbers, return the sum of all the numbers in the array. Use a loop for this task.

Examples

sumArray([1, 2, 3, 4]) → 10
sumArray([10, -5, 2]) → 7
sumArray([]) → 0

Starter code

function sumArray(arr) {

}

Complexity of the optimal solution

Time O(n), space O(1). The function iterates through the array once to sum its elements. The time is proportional to the number of elements (n). It uses a single variable for the sum, so space is constant.

Solve sumArray in the browser