How to enter a number (x) and add up all the previous numbers?

Asked

Viewed 35 times

0

How to enter a number and make the sum of all previous numbers, EXAMPLE: I enter the number 5, it will add up to 0+1+2+3+4 = 10 ! He will add and give the answer.

I have to use the FOR command.

My command has gone like this, but it’s not correct.

function somatoria(x){
  var soma = 0;

  for(var i = 0;  i < x;  i++) {
  soma = i +  i;}

  return soma;
}
  • Tries soma += i

  • 1

    soma = soma + i; or, simplifying, soma += i

  • The only difference for this one is that it goes 2 in 2 and here goes in 1, which in this part is already right.

  • It worked out guys, so much that I messed up the code, I gave this shot, plus Brigadeo, people.

  • It just doesn’t make sense to start the variable i of the tie with 0, since 0 does not change the result. Then it could be var i = 1.

  • Function somatoria(x){ var soma = 0; for(var i = 0; i < x; i++) { soma = sum + i;} Return soma; }

Show 1 more comment
No answers

Browser other questions tagged

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