ChromeBrowser
ChromeBrowser

Reputation: 219

while loop to print out only odd numbers in javascript

let number = 0;

while (true) {
    if (number%2 === 0) continue;
    console.log(number);
    number ++;
}

I wanted to infinite loop to print out only odd numbers. But this doesn't seem to work. What am I doing wrong?

Upvotes: 0

Views: 7814

Answers (5)

shrihankp
shrihankp

Reputation: 500

Let's have a brief understanding of the code execution.

When the following code is executed...:

let number = 0;

while (true) {
    if (number%2 === 0) continue;
    console.log(number);
    number ++;
}

...the following happens:

  1. The first line allocates memory for a variable named number and stores a value of 0.
  2. The while loop starts, and it checks whether the condition is true, and yes it is, and always will be, as the condition is simply true.
  3. Then, it checks whether the number mod 2 returns 0, and definitely, it does, since 0÷2 is 0 and the remainder is 0, so the condition inside the if statement is true, and therefore it executes the code correspondingly. When it sees continue, it jumps back to step 2 and checks the while loop condition, then comes back here, then goes back to step 2, then again comes back here and this never ends(ends when you stop the code execution or close your browser obviously).

Simply put, it never goes forward to the console.log and the number++ line. This is why your code isn't working.

The code from others work because the control actually moves forward in the code and never actually becomes stuck in the above loop.

Upvotes: 1

Wt.N
Wt.N

Reputation: 1658

Whatever number is, increment it first. Otherwise, when it is even, it never reaches to number++ any more.

let number = 0;

while (true) {
    number ++;
    if (number%2 === 0) continue;
    console.log(number);
}

Upvotes: 1

Papai from BEKOAIL
Papai from BEKOAIL

Reputation: 1529

You should increment the number when it is even also, to check the next number and so on:

      let number = 0;

      while (true) {
         if (number%2 === 0){
            number++;
            continue;
         }
         console.log(number);
         number ++;
      }

Upvotes: 1

Azad
Azad

Reputation: 5264

let number = 0;

while (true){ 
    if (++number % 2 == 1){
        console.log(number);
    }
}

no need a continue statement, just check the remainder is 1 the print the value in the loop. you can further shorten the if condition as if (++number % 2)

Upvotes: 1

iamdhavalparmar
iamdhavalparmar

Reputation: 1218

Try this code

let number = 0;

while (true) {
    if (number % 2 != 0)
        console.log(number);
    number ++;
}

The code you're using will not work because you defined number=0 and then you're checking the condition if(number%2==0) continue; so this condition will always return true because the number is defined 0 and the number++ will never increase.

Upvotes: 1

Related Questions