Java Program to Print a 9x9 Multiplication Table

Отвечено с помощью: GPT-4o-mini отJava Q&A Hub

Вопрос:

Print 9*9 multiplication table using java

Ответ:

Certainly! Below is a simple Java program that prints a 9x9 multiplication table:

public class MultiplicationTable {
    public static void main(String[] args) {
        // Print the header
        System.out.print("    ");
        for (int i = 1; i <= 9; i++) {
            System.out.printf("%4d", i);
        }
        System.out.println();

        // Print a separator line
        System.out.println("    ---------------------------------");

        // Print the multiplication table
        for (int i = 1; i <= 9; i++) {
            System.out.printf("%4d|", i); // Print the row header
            for (int j = 1; j <= 9; j++) {
                System.out.printf("%4d", i * j); // Print the product
            }
            System.out.println(); // Move to the next line
        }
    }
}

Explanation:

  1. Header: The program first prints the column headers (1 to 9).
  2. Separator: A line is printed to separate the headers from the table.
  3. Nested Loops: The outer loop iterates through the rows (1 to 9), and the inner loop iterates through the columns (1 to 9) to calculate and print the product of the current row and column indices.
  4. Formatting: The printf method is used for formatted output, ensuring that the numbers align properly in columns.

How to Run:

  1. Copy the code into a file named MultiplicationTable.java.
  2. Open a terminal or command prompt.
  3. Navigate to the directory where the file is saved.
  4. Compile the program using the command: javac MultiplicationTable.java.
  5. Run the compiled program using the command: java MultiplicationTable.

You should see the 9x9 multiplication table printed in a formatted manner.