As the another answer I said, all you had to do was increase the x
outside the if
. As it stands, your code only increases x
if he is even. But then he becomes odd and is never incremented (because he no longer enters the if
), and therefore the while
never ends.
But if you only want to print even numbers, you don’t have to increment x
one-on-one.
Just check if the first number is even (if it is not, increments), and from there, just add 2 in 2. So you already skip all the odd, avoiding if
'is unnecessary within the while
:
function pares(x, y) {
// verifica se x é par (se não for, soma 1)
if (x % 2 != 0) {
x++; // x passa a ser par
}
// nesse ponto eu garanti que x é par
while (x <= y) {
console.log(x);
x += 2; // soma 2, assim já vai para o próximo número par
}
}
pares(32, 321);
Obs: the snippet above is not showing all rows (in my browser, it is showing only from 222 to 320). But you can open your browser console to see the entire output (press F12 and choose the "Console").
You only increment x when it is even, then it becomes odd and is never incremented (and so never leaves the while). Make a table test in the code and will understand the problem :-)
– hkotsubo
Great guy, thank you so much for helping :D
– Ruan Linos Alves