Printable Answers to questions in Introduction to Multiple-Dimensional Arrays

Answers in reverse order for hypertext links are in 2Dans.html.

Answer 1.

int sum = 0;
for (int row = 0; row < 3;row++)
   for (int col = 0; col < 4; col++)
      sum += table[row][col];
Hint for question 2a.

 t is reference to an array of rows, so the number of rows is straightforward.  The number of columns is trickier.  We must actually look at one of the rows to see its size, so the number of columns is the number of elements in row 0 (or 1 or 2 or ...).   How do you state that is Java?

Answer 2a.

Since t is an array of rows,  the number of rows is t.length.
 t[0] is the initial row. Its length is t[0].length.  (Or you could replace 0 by any of the other row indices, assuming they are all the same length.)

Answer 2b.

sum2D(int[][] t) {
   int sum = 0;
   for (int row = 0; row < t.length;row++)
      for (int col = 0; col < t[0].length; col++)
         sum += t[row][col];
   return sum;
}

Answer 2c.   Getting the types right is tricky:
sum2D(int[][] t) {
   int sum = 0;
   for (int[] row : t) // t is actualy stored as a 1D array of int[]
      for (int val : row)
         sum += val;
   return sum;
}

Answer 3.

answer3(int[][] a) {
// no provision was made for the array reference a being null:
// you might assume it won't happen as I did here or check and do nothing or throw an exception
   for (int row = 0; row < a.length;row++)
      for (int col = 0; col < a[row].length; col++)
         a[row][col] = 10*(row+1) + col + 1;
}