//sample solution
function oddSum(n) {
/**Complete the code below to return the sum of
all the odd numbers from 1 to n, inclusive. **/
var sumSoFar = 0; //Keep track of the sum so far
var currentNumber = 1;
while (currentNumber<=n) {
/**Check if the number is odd and update
the variable sumSoFar appropriately.**/
if(currentNumber % 2 != 0){
sumSoFar += currentNumber;
} else {
currentNumber += 1;
}
currentNumber += 2;
}
return sumSoFar;
}
//test
oddSum(10);
No comments:
Post a Comment