How to add numbers in sequence in Javascript

Asked

Viewed 152 times

0

I’m trying to figure something out, but I can’t. It has a function that takes a parameter, this parameter has a number and is basically to sum from 1 to the number of this parameter in sequence. As in 1 + 2 + 3 + 4... and return the result of the sum of these numbers.

I’m trying to solve it this way:

function somatotal(numero) {
    for (var cont = 0; cont < numero; cont++) {
        var resultado = cont + 1
        return resultado         
    } 
} 

But it’s not giving.

1 answer

3

Basically your algorithm has 2 errors:

  • Does not increment the result but creates a new value;

  • Returns inside the repeat loop.

By correcting these mistakes we would have:

function somatotal(numero) {
  let resultado = 0;

  for (let cont = 1; cont <= numero; cont += 1) {
    resultado += cont;
  }
  
  return resultado;
}

console.log(somatotal(5));

  • 1

    hi, I fixed what you pointed out and it worked, thank you!

  • @Maioamarelo do not forget to accept the answer as chosen if the answer has helped you.

Browser other questions tagged

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