Write a program to print the multiplication table of the number entered by the user.

Here’s a simple Java program that prints the multiplication table for a number entered by the user:

 
				
					import java.util.Scanner;

public class MultiplicationTable {
    public static void main(String[] args) {
        // Create a Scanner object to read input from the user
        Scanner scanner = new Scanner(System.in);

        // Prompt the user to enter a number
        System.out.print("Enter a number: ");
        int number = scanner.nextInt();

        // Print the multiplication table for the entered number
        System.out.println("Multiplication table for " + number + ":");
        for (int i = 1; i <= 10; i++) {
            System.out.println(number + " x " + i + " = " + (number * i));
        }

        // Close the scanner
        scanner.close();
    }
}

				
			

Explanation

  1. Importing Scanner Class: The Scanner class from java.util package is imported to read input from the user.
  2. Creating Scanner Object: A Scanner object named scanner is created to read input from the standard input stream (keyboard).
  3. Prompt User for Input: The program prompts the user to enter a number.
  4. Read the Input: The entered number is read and stored in the variable number.
  5. Print Multiplication Table: A for-loop is used to iterate from 1 to 10, and in each iteration, the multiplication result is printed in the format: number x i = result.
  6. Close the Scanner: Finally, the scanner object is closed to free the associated resources.

How to Run the Program

  1. Copy the code into a file named MultiplicationTable.java.
  2. Open a terminal or command prompt.
  3. Navigate to the directory containing the MultiplicationTable.java file.
  4. Compile the program using the command: javac MultiplicationTable.java
  5. Run the compiled program using the command: java MultiplicationTable
  6. Enter a number when prompted, and the multiplication table for that number will be displayed.

Out Put

				
					Enter a number: 5
Multiplication table for 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

				
			

Explanation of the Output

  1. User Input Prompt: The program prompts the user with Enter a number:.
  2. User Input: The user types 5 and presses Enter.
  3. Multiplication Table: The program then prints the multiplication table for the number 5, from  5 x 1 to 5 x 10.

This output matches the behavior described in the program: it reads an integer from the user, and then prints out the multiplication table for that integer. Each line of the multiplication table shows the result of multiplying the input number by the current value of the loop variable i, which ranges from 1 to 10.

Scroll to Top