Display Multiplication Table in Java

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Loops

What You’ll Learn

A times table is a short loop: for each row index i, print base x i = base * i. This tutorial covers fixed and interactive bases, a custom row limit, a live preview, worked Java examples, edge cases, and complexity.

Definition

Times table

Rows of products for one base number.

For Loop

i = 1..last

Repeat the same print pattern for each row.

Format

base x i =

Clear output rows that match school tables.

Input

Validate n

Read a positive integer and reject bad input when needed.

Live Preview

Any base

Print rows 1 through 10 for a base you choose.

O(k) Cost

O(1) space

Linear in the number of printed rows.

Introduction

A multiplication table for a base n is the list of products n x 1, n x 2, and so on up to some limit, often 10. In code, that is a single loop that prints one formatted row per multiplier.

Interviews use this to check loops, string formatting, and simple input validation, not fancy math. Once the helper exists, you can swap a fixed base for user input or change how many rows you print.

Why it matters?

It is one of the cleanest ways to show you understand for loops, formatted output, and readable console programs.

Key Highlights

One Loop

Each i prints one product row.

Helper First

Reuse printMultiplicationTable.

Validate Input

Catch bad input and non-positive bases.

Flexible Limit

Pass last as 10, 12, or 20.

In short: for i from 1 to last, print base x i = base * i.

📝 Problem & Approach

Given a base number and a row limit, print each product from 1 through that limit in a readable format.

java
// base = 5, last = 10
// 5 x 1 = 5
// 5 x 2 = 10
// ...
// 5 x 10 = 50

Inputs & Outputs

ItemTypeDescription
baseintThe number whose table you print, often positive.
lastintHow many rows to print, commonly 10.
OutputtextOne line per row: base x i = product.

Minimal workflow

Pseudocode
procedure printTable(base, last):
    print heading
    for i from 1 to last:
        print base, i, and base * i

Method comparison

MethodIdeaNotes
forKnown row countInterview default, clearest
whileIncrement a counterWorks, slightly more boilerplate
Hard-coded printsTen separate linesAvoid, does not scale with last

⚡ Quick Reference

GoalPattern
Loop rowsfor (int i = 1; i <= last; i++)
Print rowSystem.out.println(base + " x " + i + " = " + (base * i));
Fixed demobase = 5, last = 10
Read baseScanner sc = new Scanner(System.in)
Reject bad inputhasNextInt() / if (n <= 0)
Align columnsSystem.out.printf("%d x %2d = %4d%n", ...)

📋 for vs while vs Hand Prints

Same table, different ways to drive the rows.

for
for (int i = 1; ...)

This page, clearest for fixed counts

while
int i = 1; while (i <= last)

Fine alternate, remember to increment

Hard-coded
10 print lines

Breaks as soon as last changes

Interview tip
helper(base, last)

Reusable method beats one-off scripts

Context

When This Problem Shows Up

Reach for a times-table loop whenever you need repeated formatted product rows.

  1. Beginner loop drills

    First programs that combine loops and print.

  2. School / lab assignments

    Print the table for a number the user types.

  3. Output formatting practice

    Build readable rows with concatenation or printf.

  4. Input validation warm-ups

    Handle invalid text and non-positive bases.

  5. Not a full grid

    One base only, nested loops are a different problem.

Key benefit: a tiny reusable helper that teaches loops, formatting, and validation in one place.

🔮 Live Preview

Default base is 5 to match Example 1. Change it and click Print table.

Prints rows from 1 to 10. Enter a whole number.

Live result
Press “Print table”.

Examples Gallery

Three complete Java programs: fixed table for 5, user-entered base, and a custom row limit with a while loop. Click View Output to reveal sample console results.

📚 Getting Started

A reusable helper and the classic 5-times table.

Example 1 — Table for 5 (Fixed Base)

Classic 5-times table from 1 to 10.

java
public class MultiplicationTableFixed {
    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) {
        int base = 5;
        int last = 10;
        printMultiplicationTable(base, last);
    }
}

How It Works

The loop visits multipliers 1 through 10. Each iteration prints one formatted product line for base 5.

⚡ Interactive Input

Read a positive integer and print its table up to 10.

Example 2 — Table for a Number You Type

Reads a positive integer and prints its table up to 10.

java
import java.util.Scanner;

public class MultiplicationTableInput {
    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: ");

        if (!sc.hasNextInt()) {
            System.out.println("Could not read an integer.");
            return;
        }

        int n = sc.nextInt();
        if (n <= 0) {
            System.out.println("Please enter a positive integer.");
            return;
        }

        printMultiplicationTable(n, 10);
    }
}

How It Works

Invalid input becomes a clear message through hasNextInt(). Non-positive values are rejected before printing, matching typical school-table rules.

⚙️ Flexible Limits

Let the caller choose how many rows to print, here with a while loop.

Example 3 — Custom Last Row With while

Prints the 7-times table through 12 using a while counter.

java
public class MultiplicationTableWhile {
    static void printMultiplicationTableWhile(int base, int last) {
        System.out.println("Multiplication table for " + base + " (up to " + last + "):");
        int i = 1;
        while (i <= last) {
            System.out.println(base + " x " + i + " = " + (base * i));
            i++;
        }
    }

    public static void main(String[] args) {
        printMultiplicationTableWhile(7, 12);
    }
}

How It Works

A while loop needs an explicit counter and i++ each pass. Prefer for when the row count is known; use while when the stop condition is more open-ended.

🧠 How the Algorithm Prints the Table

1

Choose base & last

Fix them in code or read them from input.

Setup
2

Loop i = 1..last

Walk each multiplier in order.

Loop
3

Compute product

product = base * i for the current row.

Math
=

Print the row

Output base x i = product, then continue.

🔎 Worked Walkthrough — Table of 5

Trace the first few rows for base = 5, last = 10.

ibase * iPrinted row
155 x 1 = 5
2105 x 2 = 10
3155 x 3 = 15
same pattern
10505 x 10 = 50

After i = 10, the loop ends, matching Example 1.

Use Cases

Where printing a times table shows up beyond the interview prompt.

1. Loop Warm-Ups

First clean for-loop with row output.

Example: table of 5.

2. Lab Assignments

User types a base, you print 1 through 10.

Example: Example 2 flow.

3. Formatting Drills

Practice concatenation and aligned output.

Example: printf width specifiers.

4. Validation Practice

Reject bad text and non-positive bases.

Example: hasNextInt().

5. Teaching for vs while

Same output, two loop styles.

Example: Example 3.

6. Bridge to Factorial

Another loop that multiplies repeatedly.

Example: related topic.

Pro Tip: write the helper first with fixed args, then wrap it with input, it is easier to debug.

Advantages

Why the loop-based table approach works well for beginners and interviews.

  1. 1. Tiny & Clear

    A few lines that anyone can dry-run on paper.

  2. 2. Scales With last

    Change 10 to 12 or 20 without rewriting prints.

  3. 3. Easy to Reuse

    One helper serves fixed demos and input programs.

  4. 4. Cheap

    O(last) time and O(1) extra memory.

Pro Tip: prefer for in interviews unless asked specifically for while.

Usage Tips

Small habits that keep times-table programs interview-ready.

  1. 1. Extract a Helper

    Keep printing in printMultiplicationTable(base, last).

  2. 2. Use the Bounds Correctly

    Remember i <= last is inclusive of the last row.

  3. 3. Validate Early

    Handle invalid input and non-positive bases before the loop.

  4. 4. Parameterize last

    Do not hard-code 10 inside the helper if assignments vary.

  5. 5. Align When Needed

    Use printf width specifiers for neat columns in demos.

Pro Tip: dry-run 5 x 1 through 5 x 3 aloud, if those rows match, the loop is correct.

Common Pitfalls

Mistakes that commonly break times-table programs.

  1. 1. Off-by-One Loop

    Using i < last and missing the final row.

    → Use i <= last.

  2. 2. Forgotten while Increment

    Infinite loop when i never increases.

    → Always increment inside while.

  3. 3. Unchecked Scanner Input

    Calling nextInt() on non-numeric text crashes.

    → Check hasNextInt() first.

  4. 4. Ten Hard-Coded Prints

    Copy-pasted lines that cannot change last.

    → Always use a loop.

  5. 5. Confusing With Full Grid

    Nesting loops when only one base was asked.

    → One loop is enough for one times table.

Edge Cases

Handle these before claiming the table program is complete.

Input

Non-integer text

Catch input errors and show a clear message.

Base

Zero or negative base

Decide whether to allow or reject based on assignment rules.

Last

last < 1

The loop prints nothing, validate if that is unexpected.

Large

Very large last

Still O(last), output volume grows with rows.

Zero

Base 0

Products are all 0, math works, school rules may reject it.

Neg

Negative base

Products flip sign, allow only if the problem says so.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • School convention. Many curricula stop at 10 or 12, parameterize last either way.
  • One loop is enough. A full multiplication grid needs nested loops, one base does not.
  • Related to factorial. Factorial also multiplies in a loop, but accumulates a product instead of printing rows.
  • Formatting is free. Alignment changes readability, not asymptotic cost.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Reproduce table of 5

  • Match Example 1 output exactly
  • Use a helper with last = 10

2. Add input validation

  • Reject non-integers
  • Reject n <= 0

3. Custom last

  • Ask for base and last
  • Print through that limit

4. while version

  • Rewrite Example 1 with while
  • Do not forget i++

Notes

  • Core loop: print base * i for each row index.
  • Cost: linear in the number of printed rows.
  • Extension: take both base and row limit from user input.
  • You can align outputs with fixed-width formatting. Let users choose the last row, such as 10, 12, or 20, if the assignment asks.

Quick Takeaway: loop i from 1 to last, print base x i = base * i, validate input when needed.

⏱️ Time and Space Complexity

TaskTimeExtra space
Print last rowsO(last)O(1)
Input + printO(last)O(1)
while versionO(last)O(1)

Ignoring the size of printed text, cost grows with how many rows you emit.

Wrap Up

🎉 Conclusion

A multiplication table is a short loop that prints base x i = base * i for each multiplier. Prefer a reusable helper, validate interactive input, and parameterize last when assignments ask for 12 or 20 rows.

Practice the three examples above, then continue to checking whether a number is a natural number.

for (int i = 1; i <= last; i++) print base x i = base * i.

💡 Best Practices

✅ Do

  • Use a helper with base and last
  • Prefer for for known row counts
  • Validate interactive input
  • Print clear base x i = rows
  • State O(last) time / O(1) space

❌ Don’t

  • Hard-code ten print lines
  • Forget the final row
  • Skip integer input checks
  • Forget i++ in while
  • Nest loops for one base

Key Takeaways

Knowledge Unlocked

Five things to remember about multiplication tables

Print a times table the interview-friendly way.

5
Core concepts
f 02

Format

base x i =

Output
? 03

Input

Validate n

Safety
n 04

last

Parameterize rows

Flexible
O 05

Cost

O(last) / O(1)

Analysis

❓ Frequently Asked Questions

It is a list of products like n x 1, n x 2, and so on. Each row is one multiplication.
Because the same pattern repeats for each row. Only the counter changes.
School tables often use 1 to 10. You can change the upper limit to 12 or any positive number.
Yes. A while loop works too, but for is simpler when the number of rows is known.
Multiplication still works, but classic school tables usually use positive bases. You can validate input and reject non-positive values if needed.
If you print k rows, time is O(k) and extra space is O(1), ignoring output text.
Use printf width specifiers such as %2d or %4d so numbers line up in columns.
Often yes for assignments. Keep a reusable printMultiplicationTable(base, last) helper either way.
Not for one times table. Nested loops appear when you print many bases at once as a full grid.

Did you Know? 🔊

A multiplication table for a number n is the list n x 1, n x 2, .... A loop prints these rows automatically instead of writing each line by hand.

Continue to Natural Number

Learn how to check whether a number is a natural number in Java.

Natural number tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful