0

I have an easy drill to print all the even numbers between 1-1000.

I want to set the condition in the line of the loop and not below it..

This is what I've tried:

   for (let i = 1; i <= 1000 && i % 2 == 0 ; i++) {
        document.write(i + " ");
// I dont want the condition here !!!

    }

I searched the forum and tried this too:

  for (let i = 1;( (i <= 1000) && (i % 2 == 0) ); i++) {
        document.write(i + " ");
    }

It looks like the same code I think, but there is nothing in the console when I run the code..

hyounis
  • 4,529
  • 2
  • 18
  • 16
  • Does this answer your question? [How to do a script for odd and even numbers from 1 to 1000 in Javascript?](https://stackoverflow.com/questions/26900080/how-to-do-a-script-for-odd-and-even-numbers-from-1-to-1000-in-javascript) – Luca Kiebel Feb 15 '20 at 13:40
  • control will transfer out of the loop if the condition is false so, your condition is false at first place that is why it is not showing anything – Zafeer Feb 15 '20 at 13:44

1 Answers1

4

The test condition in the loop header determines whether the loop will continue to iterate. Because the first value of i is 1, and 1 is not even, the loop body is never run.

The whole test expression must be true (well, "truthy") for the loop not to stop. Therefore, you cannot place the evenness test in the loop header. It must be a separate test inside the loop body.

Now, you could do this without a test by starting the iteration at 2 instead of 1 and adding 2 on each iteration. Then you don't need to test for evenness at all:

for (let i = 2; i <= 1000; i += 2)
  document.write(i);
Pointy
  • 405,095
  • 59
  • 585
  • 614