Why doesnt my code work?
Why does my web browser print 23 when this code is entered
Shouldn't it continue and never stop?
- 1 decade agoFavorite Answer
the program isn't printing 23, it's printing 2, and then 3. (with no space, because you haven't asked for one)
If you want it to go forever, just change the while condition to true
var x = 0
- ScorpioLv 41 decade ago
If you tried to debug your code on paper, you would have seen what is wrong!
Firstly, the output is not the number "23"..it is "2 3" printed in two separate iterations of the do..while loop. It looks like 23 because you are not printing any spaces!
Anyways, here is a dry run of your code
first x = 1 and y = 2
x = 1+ 1 = 2
Print x => Print 2
while (y >= x) --> this is true right now because y=2 and x=1
second iteration of the loop:
x = 2+1 = 3
print x => Print 3
now y>=x is false because y=2 and x=3. so loop stops.
hence the output '23'.
Now for what you want to achieve, here goes:
for(x=1;x>0;x++) --> beware, this is an infinite loop!
document.write(x+" "); --> the "+" operator is to concatenate a space after every number.
- 1 decade ago
You need to move the var y = x+1 variable inside the do loop. As it is written now, it won't update the y variable each time the x variable changes.