There are some problems with the code.
Must accumulate the values of i
and not of x
. Actually it was not accumulating, it was just adding up the initial value with the first value of the loop that is 0 also so it always gives 0. It is not performing several steps at the time it finds the return
the code closes, gives the result and does nothing else. Then you can only give the return
at the end of the loop when already executed everything.
Another problem in code that does not generate error but is inefficient and meaningless is the if
to check if the number is even, it is already known that it is, you are getting it at 0 which is even and is adding 2 at each step, so all number of i
is par.
Then you only need to boot the Accumulative Valve (soma
), the loop that will go through all the desired numbers, already skipping the odd with the o += 2
that you used and return the accumulator variable. Note that to go accumulating uses the operator +=
you already know how to use, so the variable soma
it always happens to be her value plus the new value to add up, so you do it with soma
the same thing you did with i
.
function somaDosPares(x) {
let soma = 0;
for (let i = 0; i <= x; i += 2) soma += i
return soma;
}
console.log(somaDosPares(6));
I put in the Github for future reference.
You have to solve this performatively, but to solve your algorithm you may even need to be this way to pass automatic evaluation because it’s about the for
would be this there.
Does this Answer your Question? Add a sequence of numbers
– Gato de Schrödinger