Write a program to create a rectangular array containing a multiplication table from 1 x 1 up to 12 x 12.
Output the table as 13 columns with the numeric values right-aligned in the columns.
(The first line of output is the column headings, the first column with no heading, then the numbers 1 to 12 for the remaining columns. The first item in each of the succeeding lines is the row heading, which ranges from 1 to 12.)
Output of Above Java Program
Output the table as 13 columns with the numeric values right-aligned in the columns.
(The first line of output is the column headings, the first column with no heading, then the numbers 1 to 12 for the remaining columns. The first item in each of the succeeding lines is the row heading, which ranges from 1 to 12.)
public class Tables { public static void main(String[]args) { final int TABLE_SIZE = 12; // Declare the rectangular array to store the multiplication table: int[][] table = new int[TABLE_SIZE][TABLE_SIZE]; // Fill in the array with the multiplication table: for(int i = 0 ; i < table.length ; ++i) { for(int j = 0 ; j < table[i].length ; ++j) { table[i][j] = (i+1)*(j+1); } } // Output the table heading System.out.print(" :"); // Row name column heading for(int j = 1 ; j <= table[0].length ; ++j) { System.out.print((j<10 ? " ": " ") + j); } System.out.println("\n-------------------------------------------------------"); // Output the table contents // Each entry in the table should be four characters wide so we output // three spaces preceding values less than 10, two spaces preceding values // from 10 to 99 and one space for values exceeding 100. for(int i = 0 ; i < table.length ; ++i) { System.out.print("Row" + (i<9 ? " ":" ") + (i+1) + ":"); for(int j = 0; j < table[i].length; ++j) { System.out.print((table[i][j] < 10 ? " " : table[i][j] < 100 ? " " : " ") + table[i][j]); } System.out.println(); } } }
Output of Above Java Program
: 1 2 3 4 5 6 7 8 9 10 11 12 ------------------------------------------------------- Row 1: 1 2 3 4 5 6 7 8 9 10 11 12 Row 2: 2 4 6 8 10 12 14 16 18 20 22 24 Row 3: 3 6 9 12 15 18 21 24 27 30 33 36 Row 4: 4 8 12 16 20 24 28 32 36 40 44 48 Row 5: 5 10 15 20 25 30 35 40 45 50 55 60 Row 6: 6 12 18 24 30 36 42 48 54 60 66 72 Row 7: 7 14 21 28 35 42 49 56 63 70 77 84 Row 8: 8 16 24 32 40 48 56 64 72 80 88 96 Row 9: 9 18 27 36 45 54 63 72 81 90 99 108 Row 10: 10 20 30 40 50 60 70 80 90 100 110 120 Row 11: 11 22 33 44 55 66 77 88 99 110 121 132 Row 12: 12 24 36 48 60 72 84 96 108 120 132 144