Sunday, July 14, 2024
HomeLanguagesJavascriptJavaScript Program to print multiplication table of a number

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.

Print multiplication table of a number

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

Method 1: Using Javascript Loops

Example: Display Multiplication table up to 10:

Javascript




<script>
    // Javascript program to print
    // table of a number
     
    let n = 5;
    for (let i = 1; i <= 10; ++i)
        console.log(n + " * " + i +
            " = " + n * i);
</script>


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

Method 2: Using Recursion in Javascript

Example 1: Display Multiplication table up to 10 using recursion:

Javascript




<script>
    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);
</script>


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: Display multiplication table up to a given range:

Javascript




<script>
    let n = 8;
     
    // Change here to
    // change result.
    let range = 12;
    for (let i = 1; i <= range; ++i)
        console.log(n + " * " + i +
            " = " + n * i);
</script>


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

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments