JavaScript Program to print multiplication table of a number
In this article, we are given a number n as input, we need to print its table.
Examples:
Input : 5
Output : 5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Input : 8
Output : 8 * 1 = 8
8 * 2 = 16
8 * 3 = 24
8 * 4 = 32
8 * 5 = 40
8 * 6 = 48
8 * 7 = 56
8 * 8 = 64
8 * 9 = 72
8 * 10 = 80
8 * 11 = 88
8 * 12 = 96
These are the following methods to print table:
Table of Content
- Using Javascript Loops
- Using Recursion in Javascript
- Using Array.from() method
Using Javascript Loops
In this approach we are using for loop for printing the table of the given integer. We will create a for loop and we start the iteration form 1 till 10. and print the fomat of the table.
Example: This example shows the implementation of the above-explained approach.
// Javascript program to print
// table of a number
let n = 5;
for (let i = 1; i <= 10; ++i)
console.log(n + " * " + i +
" = " + n * i);
Output
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 5 * 10 = 50
Using Recursion in Javascript
In this approach, we are using recursion to print the table. we will take the integer and the iteration value as a parameter in the recursive function. and we will print the table until it reaches to the basecase.
Example 1: This example shows the implementation of the above-explained approach.
function print_table(n, i = 1) {
if (i == 11) // Base case
return;
console.log(n + " * " + i + " = " + n * i);
i++; // Increment i
print_table(n, i);
}
// Driver Code
let n = 5;
print_table(n);
Output
5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 5 * 10 = 50
Example 2: This example show the multiplication table of 8.
let n = 8;
// Change here to
// change result.
let range = 12;
for (let i = 1; i <= range; ++i)
console.log(n + " * " + i +
" = " + n * i);
Output
8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 8 * 9 = 72 8 * 10 = 80 8 * 11 = 88 8 * 12 = 96
Using Array.from() method
In this approach we define a function printMultiplicationTable that takes a number as input and uses Array.from to create an array of length 10. The map function is then used to iterate over this array and for each index i, it prints the multiplication of the input number.
Example 2: This example show the multiplication table of 12.
function printMultiplicationTable(num) {
Array.from({ length: 10 }, (_, i) => console.log(`${num} * ${i + 1} = ${
num * (i + 1)}`));
}
printMultiplicationTable(12);
Output
12 * 1 = 12 12 * 2 = 24 12 * 3 = 36 12 * 4 = 48 12 * 5 = 60 12 * 6 = 72 12 * 7 = 84 12 * 8 = 96 12 * 9 = 108 12 * 10 = 120
Contact Us