JavaScript for Loop Example: Multiplication Table (Number 5)
The for loop in JavaScript can be used to generate a multiplication table for a specified number.
Here's an example of generating a multiplication table for the number 5:
// Number for multiplication table
var number = 5;
// Generating multiplication table using for loop
var table = "<table>";
table += "<tr><th>Multiplication Table for " + number + "</th></tr>";
for (var i = 1; i <= 10; i++) {
table += "<tr><td>" + number + " × " + i + " = " + (number * i) + "</td></tr>";
}
table += "</table>";
// Displaying the table on the webpage
document.body.innerHTML += table;
Explanation of the example:
var number = 5;: Specifies the number for which the multiplication table is generated.var table = "<table>"; ... document.body.innerHTML += table;: Constructs an HTML table (<table>...</table>) dynamically using aforloop to generate a multiplication table for the specified number and displays it on the webpage.for (var i = 1; i <= 10; i++) { ... }: Initializesito1, iterates as long asiis less than or equal to10, incrementsiafter each iteration.table += "<tr><td>" + number + " × " + i + " = " + (number * i) + "</td></tr>";: Adds each multiplication operation and result wrapped in<tr><td>tags to thetablestring for each row of the table.document.body.innerHTML += table;: Updates the HTML content ofdocument.bodyto append thetablestring containing the HTML table of the multiplication table.
All in one Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>For loop</title>
</head>
<body>
<script>
for(var i=1;i<10;i++){
document.write("<br>"+i+") Hello World");
}
</script>
</body>
</html>
Run Code