Quotes help make search much faster. Example: "Practice Makes Perfect"

Friday, December 7, 2012

LearnStreet Javascript Lesson 6 Exercise 2


//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


This is an example of scrolling text using Javascript.

Popular Posts