Reputation: 1
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);
Upvotes: 0
Views: 1257
Reputation: 44
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.
Upvotes: 0