'Running sum until a negative number
Please how can I use the index 0 in a for-loop when testing an empty array for a drumming sum. Also, the single negative value returns zero The sum should stop when a negative number is encountered
let sum = 0;
let lenArr = arr.length;
for (let i = 0; i <= lenArr - 1; i++) {
if (lenArr === 0) {
break;
}
if (arr[i] > 0) {
sum = sum + arr[i];
} else {
break;
}
}
return sum;
}
let input = [];
runningSum(input);
Solution 1:[1]
For an empty array the for loop would not be executed and it will return 0. You can remove the if condition to check length of array inside for loop.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vishal |
