Multiplication Table Generator
==== Js code separated from html code ====
Multiplication Table Generator
function createMultiplicationTable(rows, columns) {
let html = '';
for(let rowNumber = 1; rowNumber <= rows; rowNumber++) {
html = html + '';
for(let columnNumber = 1; columnNumber <= columns; columnNumber++) {
html = html + `${rowNumber * columnNumber} `;
}
html = html + ' ';
}
html = html + '
';
return html;
}
function onGeneratePressed() {
let rowsInput = document.getElementById("rows-input").value;
let columnsInput = document.getElementById("columns-input").value;
let rows = Number(rowsInput);
let columns = Number(columnsInput);
if (isNaN(rows) || isNaN(columns)) {
alert("Invalid input! Please enter numbers only.");
return;
}
let tableHTML = createMultiplicationTable(rows, columns);
document.getElementById("table-container").innerHTML = tableHTML;
}
===== For server side (node.js) =====
First you need to [[.node-js:setup|setup your node.js project]]
Then create a src folder and inside it place index.js and generateTable.js:
export function createMultiplicationTable(rows, columns) {
let tableString = '';
for(let rowNumber = 1; rowNumber <= rows; rowNumber++) {
for(let columnNumber = 1; columnNumber <= columns; columnNumber++) {
tableString = tableString + ` ${rowNumber * columnNumber} `;
}
tableString = tableString + '\n';
}
return tableString;
}
import { createMultiplicationTable } from "./generateTable.js";
let args = process.argv.slice(2);
let rowsInput = args[0];
let columnsInput = args[1];
let rows = Number(rowsInput);
let columns = Number(columnsInput);
if (isNaN(rows) || isNaN(columns)) {
console.log("Invalid input! Please enter numbers only.");
}
else {
let tableString = createMultiplicationTable(rows, columns);
console.log(tableString);
}
To run the code, from the project root folder:
node src/index.js 5 5
Will output in the console:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25