</>

Technology

Java Programs

Difficulty

Beginner

Interview Question

Write a Java program to print the multiplication table of a given number.

Answer

Multiplication Table in Java

Java
public class MultiplicationTable {
    public static void main(String[] args) {
        int n = 5;

        System.out.println("Multiplication table of " + n + ":");

        for (int i = 1; i <= 10; i++) {
            System.out.println(n + " x " + i + " = " + (n * i));
        }
    }
}

Output

CODE
Multiplication table of 5:
5 x 1  = 5
5 x 2  = 10
5 x 3  = 15
5 x 4  = 20
5 x 5  = 25
5 x 6  = 30
5 x 7  = 35
5 x 8  = 40
5 x 9  = 45
5 x 10 = 50

Using Scanner (User Input)

Java
import java.util.Scanner;

Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();

for (int i = 1; i <= 10; i++) {
    System.out.printf("%d x %2d = %3d%n", n, i, n * i);
}

Print Tables for 1 to 10

Java
for (int n = 1; n <= 10; n++) {
    System.out.println("\nTable of " + n + ":");
    for (int i = 1; i <= 10; i++) {
        System.out.printf("%2d x %2d = %3d%n", n, i, n * i);
    }
}

Print in Grid Format

Java
// Header
System.out.printf("%-5s", " ");
for (int i = 1; i <= 10; i++) System.out.printf("%-5d", i);
System.out.println();

// Rows
for (int n = 1; n <= 10; n++) {
    System.out.printf("%-5d", n);
    for (int i = 1; i <= 10; i++) {
        System.out.printf("%-5d", n * i);
    }
    System.out.println();
}

Output (partial)

CODE
      1    2    3    4    5    ...
1     1    2    3    4    5    ...
2     2    4    6    8    10   ...
3     3    6    9    12   15   ...

Follow AutomateQA