In this post, we are going to see how to write a simple JavaScript program to generate a Multiplication table. The output will generate something like this,
Multiplication Table
| × | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
|---|---|---|---|---|---|---|---|---|---|---|
| 1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 2 | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
| 3 | 3 | 6 | 9 | 12 | 15 | 18 | 21 | 24 | 27 | 30 |
| 4 | 4 | 8 | 12 | 16 | 20 | 24 | 28 | 32 | 36 | 40 |
| 5 | 5 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 |
| 6 | 6 | 12 | 18 | 24 | 30 | 36 | 42 | 48 | 54 | 60 |
| 7 | 7 | 14 | 21 | 28 | 35 | 42 | 49 | 56 | 63 | 70 |
| 8 | 8 | 16 | 24 | 32 | 40 | 48 | 56 | 64 | 72 | 80 |
| 9 | 9 | 18 | 27 | 36 | 45 | 54 | 63 | 72 | 81 | 90 |
| 10 | 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 |
Let’s see how can we generate a multiplication table using JavaScript and display it on a webpage:
<!DOCTYPE html>
<html>
<head>
<title>Multiplication Table</title>
</head>
<body>
<h2>Multiplication Table</h2>
<table border="1">
<thead>
<tr>
<th>×</th>
<!-- Header row for the table -->
<script>
for (let i = 1; i <= 10; i++) {
document.write('<th>' + i + '</th>');
}
</script>
</tr>
</thead>
<tbody>
<!-- Generate table rows and cells -->
<script>
for (let i = 1; i <= 10; i++) {
document.write('<tr>');
document.write('<th>' + i + '</th>'); // Leftmost cell in each row
for (let j = 1; j <= 10; j++) {
document.write('<td>' + (i * j) + '</td>'); // Multiply and fill cells
}
document.write('</tr>');
}
</script>
</tbody>
</table>
</body>
</html>
Copy and paste this code into an HTML file, and then open the file in a web browser. It will display a multiplication table from 1 to 10. The JavaScript code within the <script> tags generate the table structure and populate it with the multiplication values. The table headers and cells are created dynamically using loops.
Thanks for Reading…