Multiplication Table

import java.util.Scanner;

public class MultiplicationTable {
    public static void main(String[] args) {
        try (Scanner scan = new Scanner(System.in)) {
            while (true) {
                // Display menu
                System.out.println("\n==== Multiplication Table Options ====");
                System.out.println("A: Use For Loop");
                System.out.println("B: Use While Loop");
                System.out.println("C: Use Do-While Loop");
                System.out.println("X: Exit Program");
                System.out.println("=======================================");
                System.out.print("Enter your choice (A/B/C/X): ");

                // Get user input and convert to uppercase
                String choice = scan.nextLine().trim().toUpperCase();

                // Process user input
                switch (choice) {
                    case "A":
                        printUsingForLoop();
                        break;
                    case "B":
                        printUsingWhileLoop();
                        break;
                    case "C":
                        printUsingDoWhileLoop();
                        break;
                    case "X":
                        System.out.println("Program exited. Goodbye!");
                        return;
                    default:
                        System.out.println("Invalid choice! Please enter A, B, C, or X.");
                }
            }
        }
    }

    // ✅ Method A: Using For Loop
    public static void printUsingForLoop() {
        System.out.println("\n==== Multiplication Table (For Loop) ====\n");
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.printf("%d×%d=%-4d", j, i, i * j);
            }
            System.out.println();
        }
    }

    // ✅ Method B: Using While Loop
    public static void printUsingWhileLoop() {
        System.out.println("\n==== Multiplication Table (While Loop) ====\n");
        int i = 1;
        while (i <= 9) {
            int j = 1;
            while (j <= i) {
                System.out.printf("%d×%d=%-4d", j, i, i * j);
                j++;
            }
            System.out.println();
            i++;
        }
    }

    // ✅ Method C: Using Do-While Loop
    public static void printUsingDoWhileLoop() {
        System.out.println("\n==== Multiplication Table (Do-While Loop) ====\n");
        int i = 1;
        do {
            int j = 1;
            do {
                System.out.printf("%d×%d=%-4d", j, i, i * j);
                j++;
            } while (j <= i);
            System.out.println();
            i++;
        } while (i <= 9);
    }
}

Scroll to Top