JavaScript – Exercise 10 : The While Loop

Just as the “for loop” repeated all the statements within the loop body, “while loop” also does the same thing. It is another type of loop that repeats everything inside the loop until the loop condition is false.

The typical structure of while loop is given below.

n = 10
i = 0
While( i < n)
{
   
statement 1
statement 2
.
.
.
statement n
i++
   
}

The working of the “While Loop” is easy to understand using an example program. So we are going to create a page that will make use of JavaScript and do some action with “While Loop”. We call this web page as “loop2.HTML”.

The JavaScript Code

<script "text/JavaScript">
var i=0;

while(i<=5)
{

    document.write("The Value of I is"+ i);

    document.write("<br/>");

i++;

}

</script>

The JavaScript code that we are going to use is as follows.

The while loop has the statement ‘The Value of I isĀ + i’ which is repeated n times when the loop executes.

The HTML file – loop2.HTML

Now we give the code for HTML file that contains the above JavaScript code.

<html>
<head>  
<title>The While Loop</title>
<script type="text/JavaScript">
var i=0;
while(i<=5)
{

    document.write("The Value of I is"+ i);            
    document.write("<br/>");
i++;
       
}
   
</script>
</head>
<body>
<p> THIS IS TEST USING AN INTERNAL JAVA SCRIPT</p>
</body>
</html>

The page when loaded to browser will produce the following output. If you do not get the correct output then your browser does not support JavaScript or there may be something wrong with your code.

Output

Output - While Loop
Output – While Loop
Advertisements