0

Where I go wrong?

I have to write a code for a function that calculate sum of only positive numbers or if there is nothing then return 0 here is code function positiveSum(arr) { var sum; for(let i=0; i <= arr.length; i++){ let temp = arr[i]; if(temp > 0){ sum+=arr[i] } else { sum = 0; } } return sum; }

5th Feb 2023, 5:00 AM
Girish Sahu
Girish Sahu - avatar
3 Answers
+ 3
And initialize <sum> once just before the loop starts var sum = 0;
5th Feb 2023, 6:01 AM
Ipang
+ 2
when temp is not positive, you are reseting the sum to 0
5th Feb 2023, 5:06 AM
arturop200
arturop200 - avatar
0
Your code is almost correct. You need to initialize the value of sum to 0 before starting the loop. If arr is an empty array, then sum should remain 0, otherwise it will result in undefined. Here is the corrected code: function positiveSum(arr) { var sum = 0; for(let i=0; i < arr.length; i++){ let temp = arr[i]; if(temp > 0){ sum+=arr[i] } } return sum; }
5th Feb 2023, 10:28 AM
ArsenicolupinIII