JavaScript While Loop
Loops - While Loop
while :
'while' loop is used when the block of code is to be executed as long as the specified condition is true. To implement the same, we use the following syntax:
The value for the variable used in the test condition should be updated inside the loop only.
Below example shows incrementing variable counter 5 times using while loop.
Also, shown below is output for every iteration of the loop.
Demo :
CODE/PROGRAM/EXAMPLE
<html>
<head>
<style>
div#maincontent {
height: 200px;
width: 500px;
border: 1px solid #CEE2FA;
text-align: left;
color: #08438E;
font-family: calibri;
font-size: 20;
padding: 5px;
}
div#heading {
text-decoration: bold;
text-align: center;
margin-top: 80px;
width: 500px;
border: 1px solid #CEE2FA;
text-align: center;
color: #08438E;
background-color: #CEE2FA;
font-family: calibri;
font-size: 20;
padding: 5px;
}
h2 {
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<center>
<div id="heading">
<h2>Booking Summary</h2>
</div>
<div id="maincontent">
<script>
var seats = 3;
var costPerTicket = 320;
var discount = 10;
var total = seats * costPerTicket;
const percent = 100;
var discountedCost;
totalCost = 0;
document.write(
"Actual cost per ticket: Rs." + costPerTicket + "<br><br>"
); //Requirement 2 b: Calculating discount based on the sequence of customers booking the ticket
index = 1;
while (index <= seats) {
discountedCost =
costPerTicket - (discount / percent) * costPerTicket;
document.write(discount + " % off on ticket " + index + "<br>");
totalCost = totalCost + discountedCost;
discount = discount + 2;
index++;
}
document.write(
"<br>" + "Actual amount for " + seats + " tickets: Rs." + total
);
document.write("<br>" + "Amount payable: Rs." + totalCost);
</script>
</div>
</center>
</body>
</html>