The number of columns in a particular row is given by specifying the row index in brackets and then finding the length:
myArray[0].length // gives the number of columns in row 0 myArray[1].length // gives the number of columns in row 1
The following code will print out all the values stored in the array, row by row:
for (int row = 0; row < myArray.length; ++row) { for (int col = 0; col < myArray[row].length; ++col) { System.out.print(myArray[row][col] + " "); } System.out.println(); }
The output of the code above would be:
3 8 -7 -6 5 4
The following code will print out all the values stored in the array, column by column:
int row = 0; for (int col = 0; col < myArray[row].length; ++col) { for (row = 0; row < myArray.length; ++row) { System.out.print(myArray[row][col] + " "); } System.out.println(); }
The output of the code above would be:
3 -6 8 5 -7 4
The following code will find and print the sum of the values in row 1 of the array:
int sum = 0; int row = 1; for (int col = 0; col < myArray[row].length; ++col) { sum += myArray[row][col]; } System.out.println("The sum of the values in row " + row + " is " + sum);
The output of the code above would be:
The sum of the values in row 1 is 4
The following code will find and print the sum of the values in column 2 of the array:
int sum = 0; int col = 2; for (int row = 0; row < myArray.length; ++row) { sum += myArray[row][col]; } System.out.println("The sum of the values in column " + col + " is " + sum);
The output of the code above would be:
The sum of the values in column 2 is -3
Homework
Read pp. 409-430 of the text.
Read the following document (double click the document to see both pages) about Magic Squares, and write a program that creates and displays a 7 by 7 Magic Square using the method described. What's special about a magic square is that the sum of the numbers in any row, column or diagonal is the same. For example, the 3 by 3 Magic Square shown below has row sums, column sums and diagonal sums of 15:
The 5 by 5 Magic Square shown below has row sums, column sums and diagonal sums of 65: