-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsumOfArray.js
More file actions
31 lines (24 loc) · 789 Bytes
/
sumOfArray.js
File metadata and controls
31 lines (24 loc) · 789 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Write a function that takes an array of numbers and returns the sum of the numbers. The numbers can be negative or non-integer. If the array does not contain any numbers then you should return 0.
// Examples
// Input: [1, 5.2, 4, 0, -1]
// Output: 9.2
// Input: []
// Output: 0
// Input: [-2.398]
// Output: -2.398
// Assumptions
// You can assume that you are only given numbers.
// You cannot assume the size of the array.
// You can assume that you do get an array and if the array is empty, return 0.
//SOLUTION
function sum(numbers) {
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return sum;
}
// Start with sum = 0.
// Loop through the array using for.
// Add each number to sum.
// Return the final result.