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

2

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you i understand =] !!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.