Reputation: 103
I'm trying to create a 12x12 times table chart using a two dimensional array. I tried the below code to actually create the array:
int[][] table = new int[12][12];
for (int row=0; row<12; row++){
for (int col=0; col<12; col++){
table[row][col] = row+1 * col+1;
}
}
Now I can't quite figure out how to display it properly, I tried this:
for(int row=0; row<table.length; row++) {
for(int col=0; col<table[row].length; col++)
System.out.print(table[row][col] + "\t");
System.out.println();
}
This gives a 12x12 table but there is no multiplication going on, the 12x12 spot (12th col 12th row in grid) is 23 instead of 144, which now makes me think the actual array is wrong. Any ideas?
Upvotes: 0
Views: 8674
Reputation: 285403
Use parentheses in your math statement. Know that multiplication has precedence over addition.
So your line of code:
table[row][col] = row+1 * col+1;
is equivalent to
table[row][col] = row + (1 * col) + 1;
Which is not what you want. You want:
table[row][col] = (row + 1) * (col + 1);
As an aside, consider using String.format(...)
or System.out.printf(...)
for formatting your output since it is much more powerful and flexible than using tabs, \t
. Also, at your stage in the game, you should enclose all if blocks and all loops inside of {...}
curly braces as this will save your tail at a later date.
e.g.,
for (int row = 0; row < table.length; row++) {
for (int col = 0; col < table[row].length; col++) {
System.out.printf("%6d", table[row][col]);
}
System.out.println();
}
or if you want the output right justified, change "%6d"
to "%-6d"
Upvotes: 3