Javascript Function Creation Question 8

Introduction

Create a function that adds up all numbers from 1 to num.

function simpleAdding(num) { 
    //your code here
}

// Output
console.log(simpleAdding(12));


// Solution 1 - For Loop
function simpleAdding(num) { 
    var i,
        result = 0;
    
    for (i = 1; i < num + 1; i++) {
      result += i; 
    }

    return result; 
}

// Output
console.log(simpleAdding(12));
// => 78

Another solution



// Solution 2 - While Loop
function simpleAdding(num) {
    var count = 0,
        result = 0;
   
    while (count < num + 1) {
        result += count;
        count += 1;
    }
    
    return result;
}

// Output
console.log(simpleAdding(12));
// => 78



PreviousNext

Related