Display Multiplication Table in JavaScript
What you’ll learn
- How to print a times table with a simple
forloop. - A clean row format:
base x i = product. - Two examples: fixed base and user-selected base, plus live preview and tryit pages.
Overview
For a base number n, print n x 1 through n x 10. The loop counter changes, the formula stays the same.
Live preview
Default base is 5. Change it and print 1 to 10.
Algorithm
Goal: print base x i for i = 1..10.
📜 Pseudocode
Pseudocode
procedure printTable(base, last):
for i from 1 to last:
print base, i, base * i1
Table for 5 (fixed base)
JavaScript
function printMultiplicationTable(base, last) {
console.log("Multiplication table for " + base + ":");
for (let i = 1; i <= last; i++) {
console.log(base + " x " + i + " = " + base * i);
}
}
const base = 5;
const last = 10;
printMultiplicationTable(base, last);2
Table for a number you choose
JavaScript
function printMultiplicationTable(base, last) {
console.log("Multiplication table for " + base + ":");
for (let i = 1; i <= last; i++) {
console.log(base + " x " + i + " = " + base * i);
}
}
const raw = prompt("Enter a positive integer:");
const n = Number(raw);
if (!Number.isInteger(n) || n <= 0) {
console.log("Please enter a positive integer.");
} else {
printMultiplicationTable(n, 10);
}❓ FAQ
It lists products for one base number, such as n x 1, n x 2, and so on, usually up to 10.
Each row follows the same formula base * i. A loop changes only i and prints all rows cleanly.
That is a common school convention. You can print to 12, 20, or any positive limit.
Yes, multiplication still works. Many beginner programs restrict input to positive values for familiar classroom output.
Either works. for is convenient when you know the exact range, like 1 through 10.
Printing k rows is O(k) time and O(1) extra space besides the output text.
Edge cases
Invalid input
Not an integer
Show a clear message instead of printing bad rows.
Range
Large values
Products get large quickly; keep examples in a practical range.
⏱️ Time and space complexity
| Task | Time | Extra space |
|---|---|---|
| Print 10 rows | O(10) (constant) | O(1) |
Summary
- Core loop: print
base x ifor each row. - Pattern: same expression each line, only
ichanges.
Did you know?
A multiplication table for a number n is just repeated products: n x 1, n x 2, and so on. A loop is perfect because only the counter changes each row.
8 people found this page helpful
