SimpleTuts.com

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:

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