Friday 24 August 2018

JavaScript: while loop

while statement executes a block of statements until expression is true

Syntax
while (expression) {
      //statements
}

while.html
<!DOCTYPE html>

<html>

<head>
    <title>while loop</title>
</head>

<body>
    <script type="text/javascript">
        var number = parseInt(prompt("Enter a number", "10"));

        document.write("<h2>Even numbers from 0 to " + number + " are </h2>");

        var i = 0;

        while (i <= number) {
            document.write(i + "<br />");
            i += 2;
        }
    </script>
</body>

</html>

Load above page in browser, it prompts for a number, and print all the even numbers from 0 to the number given by user.



Previous                                                 Next                                                 Home

No comments:

Post a Comment