Daniel John Gomez Daniel John Gomez - 7 months ago 33
Java Question

Beginner Java - Creating multiplication table by looping

I was tasked to make a multiplication table from 1-10 but I was not satisfied with my code, it seems to be long:

for (int i = 1; i <= 10; i++)
{
System.out.println("1x" + i + " = " + i + "\t" + "2x" + i + " = " + (2*i)
+ "\t" + "3x" + i + " = " + (3*i) + "\t" + "4x" + i + " = " + (4*i)
+ "\t" + "5x" + i + " = " + (5*i) + "\t" + "6x" + i + " = " + (6*i)
+ "\t" + "7x" + i + " = " + (7*i) + "\t" + "8x" + i + " = " + (8*i)
+ "\t" + "9x" + i + " = " + (9*i) + "\t" + "10x" + i + " = " + (10*i));
}


Output:

1x1 = 1 2x1 = 2
1x2 = 2 2x2 = 4
etc.

Answer

This will format the table how you have it in your example code, and uses two loops:

for (int i = 1; i <= 10; i++) {
        for (int j = 1; j <= 10; j++) {
            System.out.print(i + "x" + j + "=" + (i * j) + "\t");
        }
        System.out.println();
    }

The outer loop controls the rows in the multiplication table and the inner loop controls the columns in the multiplication table. System.out.println() signifies moving into a new row of the table