Display Multiplication Table in Java
What you’ll learn
- How a loop prints times-table rows one by one.
- How to format rows like
n x i = result. - Fixed and user-input versions in Java.
Prerequisites
Basic Java loops, methods, and integer arithmetic.
- You know how a
forloop prints repeated rows. - You understand multiplication and string output formatting.
The idea
A multiplication table is a sequence of products: for a base n, print n x i for i = 1 to 10.
Live preview
Algorithm
Read base number
Use a fixed value or input from the user.
Loop 1 to 10
For each i, compute base * i.
Print row
Output in form base x i = result.
📜 Pseudocode
for i from 1 to 10:
print n, i, n*iTable for 5 (fixed)
public class Main {
static void printMultiplicationTable(int base, int last) {
System.out.println("Multiplication table for " + base + ":");
for (int i = 1; i <= last; i++) {
System.out.println(base + " x " + i + " = " + (base * i));
}
}
public static void main(String[] args) {
printMultiplicationTable(5, 10);
}
}Table for typed input
import java.util.Scanner;
public class Main {
static void printMultiplicationTable(int base, int last) {
System.out.println("Multiplication table for " + base + ":");
for (int i = 1; i <= last; i++) {
System.out.println(base + " x " + i + " = " + (base * i));
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = sc.nextInt();
if (n <= 0) {
System.out.println("Please enter a positive integer.");
return;
}
printMultiplicationTable(n, 10);
}
}Optimization notes
Keep it simple. Prefer clear loops and method extraction before micro-optimizations.
Reuse computed values. Avoid recomputing the same sub-result inside nested loops.
❓ FAQ
🔄 Input / output examples
Use the sample programs as reference: provide valid numeric input and verify the output pattern matches the problem definition.
Edge cases
Smallest valid input
Confirm behavior for minimum accepted values.
Invalid input
Guard against non-numeric or out-of-range values when input is user-provided.
⏱️ Time and space complexity
O(k) time for k printed rows, O(1) extra space.
Summary
- Use a direct Java implementation of the numeric rule.
- Validate input and test boundary cases.
- Discuss complexity clearly in interviews.
A multiplication table for n is the list n×1, n×2, .... A loop prints each line quickly and clearly.
8 people found this page helpful
