I want to make a function that receives a parameter n and returns the sum value of all terms from 1 to n

Asked

Viewed 25 times

0

I did it, but it’s not working:

function a(n) {
    for (var contador = 0; contador <= n; contador++) {
        var soma = soma + contador;
        return soma;
    }
}

1 answer

1

You forgot to return the sum out of the repeat loop. You should declare the variable out of the loop and fill in on it, as I did below. There are other ways to do this, but as you asked, as I put it, it works perfectly.

function a(n) {
  var soma = 0;
  for (var contador = 0; contador <= n; contador++) {
    var soma = soma + contador;
  }
  return soma;
}

console.log(a(5))
// Saída: 15

Browser other questions tagged

You are not signed in. Login or sign up in order to post.