Sunday, 4 March 2018

Learn How to use while loop in JavaScript

We can use the while loop when we want to check the condition at the start of the loop. The group of statements that is to be executed is specified after the condition. Now here create a Web page named WhileLoopUse.html which shows the use of use of while loop.

#####Showing the code WhileLoopUse.html file#####

<!DOCTYPE html>
<html>
<head>
<title>Using While Loop</title>
</head>
<body background="img.jpeg" text="Green">
<h1>using while loop in the script</h1>
<SCRIPT type="text/javascript">
var totalDistance=0, fare=0;
while(totalDistance<=10)
{
fare=fare+5;
totalDistance=totalDistance+2;
document.write("Rs."+fare+"for"+totalDistance+"KM distance.<br/>");
}
document.write("Thanku Very Much!!!!!!!!!!");
</SCRIPT>
</body>
</html>


Here the while loop has a condition totalDistance<=10, which checks whether or not the value of the totalDistance variable is less than or equal to 10. In the first iteration the condition is true as totalDistance is 0. As a result the group of statements specified inside the while loop is executed that is the fare variable is incremented by 5 and the value of totalDistance is incremented by 2. The condition of the while loop is evaluated again in the second iteration which is also true and as a result the values of fare and totalDistance are increment again. Note that in this way the while loop execute six times. At the end of the sixth iteration the totalDistance variable is equal to 12 and when the condition is evaluated in the seventh iteration it become false. As a result the while loop is exited and Thanku Very Much!!!! message is displayed.






No comments:

Post a Comment