Search code examples
javamultiplication

Multiplication Table Pop Up


I have messed around with my code and I still haven't found an answer to it. Format.left is just a class that puts space in between each number. I am trying to have the numbers from 1 through 4 show on the side but it keeps popping up like this:

1      2      3      4      5      6
2      4      6      8     10     12
3      6      9     12     15     18
4      8     12     16     20     24

I hope I am making sense to you guys my English is really bad.

for(cols = 1; cols <= 4; cols++)
    {
        for (rows = 1; rows <= 6; rows++)
        {
            System.out.print(Format.right(cols * rows,7));  
        }
        System.out.println();
    }

I am looking for something that briefly looks like this:

    1   2   3   4   5
1   1   2   3   4   5
2   2   4   6   8   10
3   3   6   9   12  15
4   4   8   12  16  20
5   5   10  15  20  25

Solution

  • Try this:

    for(cols = 0; cols <= 4; cols++)
    {
        for (rows = 0; rows <= 6; rows++)
        {
            if (rows == 0 || cols == 0) {
                System.out.print(Format.right(cols + rows, 7));
            }else {
                System.out.print(Format.right(cols * rows, 7));  
            }
        }
        System.out.println();
    }
    

    You wanted each row and column to be shifted by one so I simply started the loop at 0 instead of 1 and added an if statement to handle the special case of the first row / column.