Javascript Interview Question Number Sum

Introduction

Write a method that takes in an integer num and returns the sum of all integers between zero and num, up to and including num.

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

// These are tests to check that your code is working. After writing
// your solution, they should all print true.

console.log( sum_nums(1) === 1 )// ww  w. j a  v a  2 s  .  c  om
console.log( sum_nums(2) === 3 )
console.log( sum_nums(3) === 6 )
console.log( sum_nums(4) === 10 )
console.log( sum_nums(5) === 15 )



function sum_nums(num) {
  var total= 0;
  for(i=0; i<= num; i++){
    total= total + i;
  }
  return total;
}

// These are tests to check that your code is working. After writing
// your solution, they should all print true.

console.log( sum_nums(1) === 1 )
console.log( sum_nums(2) === 3 )
console.log( sum_nums(3) === 6 )
console.log( sum_nums(4) === 10 )
console.log( sum_nums(5) === 15 )



PreviousNext

Related