Reputation: 3
I'm writing a code to output the bottom right of a multiplication table...I can get the bottom left and the top right, but I get stuck trying to get the bottom right. I'm assuming that column needs to = 12, but whenever I try to input this, it gives me an error or the same answer as before. The output is supposed to look like the n's at the beginning of the code.
n
nn
nnn
public static void main(String[] args) {
// // part 3: lower-triangular multiplication table
for (int row=1; row<=12; row++) {
for (int column=1; column <= row; column++)
System.out.printf("%5d", row*column);
for (int column = row; column <= 0; column++)
System.out.printf("%3c", ' ');
System.out.println();
}
Upvotes: 0
Views: 486
Reputation: 2727
To print the bottom (or top) right of a table, we need to iterate over the full table and omit entries
The entries omitted are replaced with whitespace so that the other entries that are printed will line up correctly
To determine if an entry is in a specific area, we can compare the X (col
) and Y (row
) values against the size (size
) of the table
1 2 ... X
1
2
...
Y
Top left includes (1,1), (1,Y), and (X,1), but not (X,Y) - X+Y < size+2
(+2 comes from 1 indexed vs 0 indexed)
Bottom left includes (1,1), (1,Y), and (X,Y), but not (X,1) - X <= Y
Top right includes (1,1), (1,Y), and (X,1), but not (X,Y) - X >= Y
Bottom right includes (1,Y), (X,1), (X,Y), but not (1,1) - size-X < Y
int size = 12; //size of the multiplication table
for(int row = 1; row <= size; row++) //go row by row
{
for(int col = 1; col <= size; col++) //go column by column
if(size - col < row) //in the bottom right area
System.out.printf("%5d", row * col); //print the number
else
System.out.print(" "); //print whitespace for formatting
System.out.println(); //end of the row, go to the next line
}
Size=4
4
6 8
6 9 12
4 8 12 16
Size=12
12
22 24
30 33 36
36 40 44 48
40 45 50 55 60
42 48 54 60 66 72
42 49 56 63 70 77 84
40 48 56 64 72 80 88 96
36 45 54 63 72 81 90 99 108
30 40 50 60 70 80 90 100 110 120
22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144
Upvotes: 1