In this post, we’ll learn how to print a multiplication table in Java.
This is one of the most basic and important programs for beginners to understand loops and user input in Java.
π‘ What is a Multiplication Table?
A multiplication table is a list that shows the results of multiplying a number by 1, 2, 3, and so on.
For example, the multiplication table of 5 looks like this:
5 × 1 = 5
5 × 2 = 10
5 × 3 = 15
...
5 × 10 = 50
π§π» Java Program to Print Multiplication Table
import java.util.Scanner;
public class MultiplicationTable {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask the user for a number
System.out.print("Enter a number to print its multiplication table: ");
int number = sc.nextInt();
// Print the multiplication table
System.out.println("\nMultiplication Table of " + number + ":");
for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (number * i));
}
sc.close();
}
}
π§ Explanation of the Code
-
Scannerclass — used to take input from the user. -
forloop — runs from 1 to 10 to print 10 lines of the table. -
Inside the loop, we multiply the input number with
iand print the result.
π₯️ Sample Output
Enter a number to print its multiplication table: 5
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
π Conclusion
This simple Java program helps beginners understand how to:
-
Take input using the
Scannerclass -
Use a
forloop -
Perform basic arithmetic operations
You can modify this program to print tables for multiple numbers (like 1 to 10) or display them in a formatted way.
Comments
Post a Comment