Check Even Numbers

Asked

Viewed 3,919 times

5

I need to check the even numbers between x and y, but when I run the code it keeps loading the page eternally and shows in the console only the number x. I’m running the code on Google Chrome.

function pares(x, y) {
    while (x <= y) {
      if (x % 2 == 0) {
        console.log(x);
        x++;
      }
    }
  }
  pares(32, 321);
  • 1

    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 :-)

  • Great guy, thank you so much for helping :D

2 answers

4

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").

3


Increment the variable "x" out of your IF. Change the code as follows:

function pares(x, y) {
    while (x <= y) {
      if (x % 2 == 0) {
        console.log(x);
        
      }
	  x++;
    }
  }
  pares(32, 321);

Browser other questions tagged

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