Multiplication table
Given a size n, return the n × n multiplication table as an array of n rows, each row an array of n numbers. The value at row i, column j is i × j, with rows and columns both counting from 1. Every row holds the same count of values, so the result is square rather than triangular.
Examples
Example 1
- Input
- n = 5
- Output
[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]
Twenty-five values, and the last of them is 5 × 5 = 25.[[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]]
Example 2
- Input
- n = 3
- Output
[1,2,3] [2,4,6] [3,6,9]
Three rows of three, and the table reads the same down as across because[[1,2,3],[2,4,6],[3,6,9]]i × jisj × i.
The Code
function multiplicationTable(n) {
const rows = [];
for (let row = 1; row <= n; row++) {
const line = [];
for (let col = 1; col <= n; col++) {
line.push(row * col);
}
rows.push(line);
}
return rows;
}
multiplicationTable(5);The first 15 calls, of 37. This one does not fit on a page.
Explanation
Both counts run the full range, so neither shapes the result: the grid is square whatever n is. They decide the number in a cell instead — the reverse of the triangles, where the counters chose the positions.
- 1
rowis 1 and the inner loop is bounded byn, not byrow, socolruns the full 1 to 5. Eachline.push(row * col)writes 1 ×col, which leaves the row reading as the columns themselves.1 2 3 4 50row=1col=1 … 5
rows.push([1, 2, 3, 4, 5])
- 2
rowis 2 andcolruns 1 to 5 again — the inner bound never moves, which is why this table is square where the triangles are not.1 2 3 4 502 4 6 8 101row=2col=1 … 5
rows.push([2, 4, 6, 8, 10])
- 3
rowis 3, sorow * colgives 3, 6, 9, 12, 15. The two counters decide what is written rather than where it goes, which is the reverse of every triangle above.1 2 3 4 502 4 6 8 1013 6 9 12 152row=3col=1 … 5
rows.push([3, 6, 9, 12, 15])
- 4
rowis 4 — five more products, 4 through 20.1 2 3 4 502 4 6 8 1013 6 9 12 1524 8 12 16 203row=4col=1 … 5
rows.push([4, 8, 12, 16, 20])
- 5
rowis 5 and the last row ends on5 * 5.row++then failsrow <= n, and 25 values across 5 rows are returned.1 2 3 4 502 4 6 8 1013 6 9 12 1524 8 12 16 2035 10 15 20 254row=5col=1 … 5
return rows → 5 × 5 values
More like this
All star & number patterns examples (12) →- Star triangle The inner loop runs as far as the row number — that is the whole idea.
- Inverted triangle Same triangle, counted downwards instead of up.
- Star pyramid Leading spaces do the centring; stars go up in odd numbers.
- Star diamond A pyramid, then the same pyramid upside down — minus the shared row.
- Hollow square Fill only the border — every interior cell is a space.
- Butterfly Two wings of stars with a gap between them that closes and reopens.