2

I am trying this code to add a number starting from 1 to n using this mathematical equation:n = n(n+1) /2

var n = prompt("enter a number");

function adding(n) {
  let N = n * (n + 1) / 2;
  return N;
}
alert(adding(n));

but it's not working in prompt. It works like this:

function adding(n) {
  let N = n * (n + 1) / 2;
  return N;
}
console.log("answer", adding(100));
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 1
    `prompt` returns a string. You need to convert it to a number. `var n = Number(prompt("enter a number"))` Otherwise `n + 1`concatenates 1 to the string instead of adding 1. For `n = 2`, `n + 1` becomes 21 not 3 – adiga Feb 09 '21 at 12:06

0 Answers0