next up previous
Next: Exercises Up: Unit 07 Previous: Example: product of two

Example: sums of the rows of a matrix

We write a static method, matrixSumRows(), that takes as parameter a matrix and returns an array with one element for each row of the matrix; the element of index i of the array must be equal to the sum of the elements of row i of the matrix.

public static int[] matrixSumRows(int[][] M) {
  int[] C = new int[M.length];            // creates the array
  for (int i = 0; i < M.length; i++) {    // iterates over the rows of M
    C[i] = 0;                             // initializes the accumulator
    for (int j = 0; j < M[i].length; j++) // iterates over the elements of row i
      C[i] += M[i][j];                    // accumulates the elements of row i
  }
  return C;
}

Example of usage:

public static void main(String[] args) {
  int[][] A = {     // creates matrix A of dimension 3x3
    { 1, 2, 2 },
    { 7, 5, 9 },
    { 3, 0, 6 }
  }

  int[] B = matrixSumRows(A);
  for (int i = 0; i < B.length; i++)
    System.out.print(B[i] + " ");     // prints out the array B
  System.out.println();
}

The program prints out the following:

5 21 9


next up previous
Next: Exercises Up: Unit 07 Previous: Example: product of two