Java Program to Display Multiplication Table of a Given Number

Multiplication table

Java programs to display the multiplication table of a number have been shown here. Both the iterative and recursive approaches have been covered below.






1. Program & output to display multiplication table of a number




1.1. Java Program & output to display multiplication table of a number using iteration

Code has been copied
/**************************************
	   alphabetacoder.com
Java Program to display multiplication
table of a given number using iteration
***************************************/

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        // declare instance of Scanner class
        Scanner sc = new Scanner(System.in);

        // delclare variables
        int i, n, r;

        // take inputs
        System.out.print("Enter a number: ");
        n = sc.nextInt();
        System.out.print("Enter the range: ");
        r = sc.nextInt();

        System.out.println("\nMultiplication table of " + n + ":");
        // display table
        for (i = 1; i <= r; i++) {
            System.out.println(n + " x " + i + " = " + n * i);
        }
    }
}

Output


Enter a number: 12

Enter the range: 11


Multiplication table of 12:

12 x 1 = 12

12 x 2 = 24

12 x 3 = 36

12 x 4 = 48

12 x 5 = 60

12 x 6 = 72

12 x 7 = 84

12 x 8 = 88

12 x 9 = 108

12 x 10 = 120

12 x 11 = 132





1.2. Java Program & output to display multiplication table of a number using recursion

Code has been copied
/***************************************
	   alphabetacoder.com
Java Program to display multiplication
table of a given number using recursion
****************************************/

import java.util.Scanner;

class Main {
    // recursive function to display 
    // multiplication table
    void multiplication_table(int n, int r) {
        // exit condition of recursive call
        if (r == 0)
            return;
        // call function
        multiplication_table(n, r - 1);
        // display the line
        System.out.println(n + " x " + r + " = " + n * r);
    }
    public static void main(String[] args) {
        // declare instance of Scanner class
        Scanner sc = new Scanner(System.in);

        // declare object of Main class
        Main obj = new Main();

        // delclare variables
        int n, r;

        // take inputs
        System.out.print("Enter a number: ");
        n = sc.nextInt();
        System.out.print("Enter the range: ");
        r = sc.nextInt();

        System.out.println("\nMultiplication table of " + n + ":");
        // call function to display multiplication table
        obj.multiplication_table(n, r);
    }
}

Output


Enter a number: 17

Enter the range: 7

Multiplication table of 17:

17 x 1 = 17

17 x 2 = 34

17 x 3 = 51

17 x 4 = 68

17 x 5 = 85

17 x 6 = 102

17 x 7 = 119