Reputation: 89
function needToAdd(start, end) {
for(var i = start; i <= end; i++) {
start += i;
}
return start
};
console.log(needToAdd(1, 10));
// 56
Hey guys, I just want to find out how I can sum the ranges using a for loop in javascript. What I have here works, but it gives me 56, instead of 55. What should I change in start += i to make it so that it will give me the sum of (1 + 2 + 3... + 10) instead of ( 1 + 1 + 2 + 3 + 4.... + 10)?
Upvotes: 0
Views: 56
Reputation:
Problem is in loop you initialized i = start
in the beginning and you stored the result as start += i
. Hence your actual result
is expected + start
.
Solution 1: Use temp
variable for result and return temp
.
var sumInRange = function(a, b) {
var i = t = b;
while (a <= --i) t += i;
return t;
};
alert(sumInRange(1, 5));
alert(sumInRange(1, 10));
Solution 2: Without temp
variable
var sumInRange = function(a, b) {
if (a === b) return a;
return b + sumInRange(a, b - 1);
};
alert(sumInRange(1, 5));
alert(sumInRange(1, 10));
Upvotes: 0
Reputation: 28455
You need to update your code to following
function needToAdd(start, end) {
for(var i = start+1; i <= end; i++) {
start += i;
}
return start
}
Note: Let us say your start and end is 1. So, in this case, your loop would have executed once and have added 1 to start and would have updated it to 2. Hence, you have to execute your loop from 1 next to start.
Upvotes: 1