Java Program to Print the Multiplication Table of a Number
A multiplication table lists the results of multiplying a number by 1, 2, 3 and so on, usually up to 10. For 5 it starts 5 × 1 = 5, 5 × 2 = 10, 5 × 3 = 15.
Printing a table is a classic loop exercise: the loop counter goes from 1 to 10 and each step prints one line.
1. Print a Table Using a for Loop
The for loop keeps the counter, the condition and the increment in one line, which suits a loop that runs a known number of times. printf() formats each line; %d is replaced by a whole number and %2d pads it to two characters so the columns line up.
import java.util.Scanner;
public class MultiplicationTable {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
scanner.close();
for (int i = 1; i <= 10; i++) {
System.out.printf("%d x %2d = %d%n", number, i, number * i);
}
}
}
Enter a number: 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
2. Print a Table Using a while Loop
With a while loop, the counter is declared before the loop and increased inside it. This program also lets the user choose how far the table goes.
import java.util.Scanner;
public class MultiplicationTableWhile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
System.out.print("Print the table up to: ");
int limit = scanner.nextInt();
scanner.close();
int i = 1;
while (i <= limit) {
System.out.println(number + " x " + i + " = " + (number * i));
i++;
}
}
}
Enter a number: 8 Print the table up to: 12 8 x 1 = 8 8 x 2 = 16 8 x 3 = 24 8 x 4 = 32 8 x 5 = 40 8 x 6 = 48 8 x 7 = 56 8 x 8 = 64 8 x 9 = 72 8 x 10 = 80 8 x 11 = 88 8 x 12 = 96
3. Print Tables from 1 to 5 Using Nested Loops
A loop inside another loop prints a grid. The outer loop picks the row (1 to 10), and the inner loop prints that row for each number from 1 to 5. %4d gives every value a width of four characters.
public class MultiplicationGrid {
public static void main(String[] args) {
for (int row = 1; row <= 10; row++) {
for (int number = 1; number <= 5; number++) {
System.out.printf("%4d", number * row);
}
System.out.println();
}
}
}
1 2 3 4 5 2 4 6 8 10 3 6 9 12 15 4 8 12 16 20 5 10 15 20 25 6 12 18 24 30 7 14 21 28 35 8 16 24 32 40 9 18 27 36 45 10 20 30 40 50
4. Summary
- A multiplication table is a loop from 1 to 10 that prints
number * ion each step. - Use a
forloop when the number of steps is known; awhileloop works the same way with the counter managed by hand. printf()with widths such as%2dor%4dkeeps the columns aligned.- Nested loops print a full grid of several tables at once.