Why doesnt my code work?

Why does my web browser print 23 when this code is entered

[<html>

<body>

<script type="text/javascript">

var x=1

var y=x+1

do

{

x=x+1

document.write(x);

}

while (y>=x)

</script>

</body>

</html>]

Shouldn't it continue and never stop?

If i wanted to make a program the counted by 1 and never stopped what would i write and what language do you suggest if it cant be done in javascript

3 Answers

Relevance
  • 1 decade ago
    Favorite 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

    while(true)

    {

    document.write(x);

    }

  • 1 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

    enter loop

    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:

    <html>

    <body>

    <script type="text/javascript">

    var x=1;

    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.

    </script>

    </body>

    </html>

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

    This will do it... but be warned, this code doesn't do good things. It will continue to process the javascript and never end. Due to the nature of Javascript, the HTML won't be visible, either, until the do loop has stopped. See for yourself:

    [

    <html>

    <body>

    <script type="text/javascript">

    var x=1

    do

    {

    x=x+1

    var y=x+1

    document.write(x);

    }

    while (y>=x)

    </script>

    </body>

    </html>

    ]

Still have questions? Get your answers by asking now.