This book is now obsolete Please use CSAwesome instead.
10.6. Getting the Number of Rows and Columns¶
Arrays know their length (how many elements they can store). It is a public read-only field so you can use dot-notation to access the field (
arrayName.length). The length of the outer array is the number of rows and the length of one of the inner arrays is the number of columns.
Note that length is a field and not a method, so you don’t add parentheses after length. However, if you use parentheses after length during the exam, you won’t lose any points.
ticketInfo.length // returns the number of rows ticketInfo.length // returns the number of columns
Since for the AP CS A exam all two-dimensional arrays are rectangular arrays (arrays that have the same number of columns in each row) you can just use the length of the first inner array as the number of columns as shown by
Check your understanding
10.7. Looping Through a 2D Array¶
Since you can find out the number of rows and columns in a 2D array you can use a nested for loop (one loop inside of another loop) to loop through all of the elements of a 2D array.
Some key things to notice about this code are:
totalis declared to be a double so that the result will be a double. If
totalwas declared to be an
intthen the result would be an integer and the values after the decimal point would be thrown away.
The number of rows is
The number of columns is
The number of times this loop executes is the number of rows times the number of columns.
You can step through the code by clicking on this link1
Mixed up programs
The following has the correct code to find the largest value in a 2D array. Drag the blocks from the left into the correct order on the right and indent them as well. Check your solution by clicking on the <i>Check Me</i> button. You will be told if any of the blocks are in the wrong order or have the wrong indention.
You can step through this code using the Java Visualizer by clicking on the following link2
10.8. Use a For-Each to Loop Through an Array¶
Since 2D arrays are really arrays of arrays you can also use a nested for-each loop to loop through all elements in an array. Loop through each of the inner arrays and loop through all the values in each inner array.
In this case the
for (int colArray : a) means to loop through each element of the outer array which will set colArray to the current column array. Then you can loop through the value in the column array.
You can step through this code using the Java Visualizer by clicking on the following link3