Page 363 - AP Computer Science A, 7th edition
P. 363

follows:
int sum = 0;
for (int row = 0; row < mat.length; row++)
sum += sumArray(mat[row]);
//for each row in mat,
//add that row’s total to sum
Note how, since mat[row] is an array of int for 0 ≤ row < mat.length, you can use the sumArray method for each row in mat.
Example 2
Add 10 to each element in row 2 of matrix mat.
for (int c = 0; c < mat[2].length; c++) mat[2][c] += 10;
NOTE
1. In the for loop, you can use c < mat[k].length, where 0 ≤ k < mat.length, since each row has the same number of elements.
2. You cannot use a for-each loop here because elements are being replaced.
3. You can, however, use row-by-row array processing. Suppose you have method addTen shown below.
/∗∗ Add 10 to each int in arr ∗/ public void addTen(int[] arr)
{
for (int i = 0; i < arr.length; i++) arr[i] += 10;
}
You could add 10 to each element in row 2 with the single
















































































   361   362   363   364   365