JavaScript For Loop
Loops - For Loop
Loops :
In JavaScript code, we may have to repeat specific action some number of times.
For example, consider a variable counter which has to be incremented 5 times.
One way of doing it is, writing increment statement 5 times as shown below:
Looping statements in JavaScript helps to execute statement(s) required number of times without repeating code.
JavaScript supports popular looping statements:
Let us understand each of them in detail.
'for' loop is used when the block of code is expected to execute for a specific number of times. To implement it, use the following syntax.
Below example shows incrementing variable counter 5 times using for 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;
//height:70px;
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
for (index = 1; index <= seats; index++) {
discountedCost =
costPerTicket - (discount / percent) * costPerTicket;
document.write(discount + " % off on ticket " + index + "<br>");
totalCost = totalCost + discountedCost;
discount = discount + 2;
}
document.write(
"<br>" + "Actual amount for " + seats + " tickets: Rs." + total
);
document.write("<br>" + "Amount payable: Rs." + totalCost);
</script>
</div>
</center>
</body>
</html>