next up previous
Next: Example: sum of two Up: Unit 07 Previous: Number of rows and

Example: printing out the elements of a matrix ordered by rows and by columns

We develop two static methods, printMatrixRows() and printMatrixColumns(), that take as parameter a matrix and print out its elements ordered respectively per rows and per columns.

public static void printMatrixRows(short[][] m) {
  for (int i = 0; i < m.length; i++) {    // iterates over the rows
    for (int j = 0; j < m[0].length; j++) // iterates over the elements of row i
      System.out.print(m[i][j] + " ");    // prints the element
    System.out.println();                 // end of the row
  }
}

Note that, in order to access all elements of the matrix m, we use two nested for loops: the outermost loop iterates over the rows (using control variable i), while the innermost loop iterates over the elements of row i (using control variable j). At the end of each row, a newline character is printed out.

public static void printMatrixColumns(short[][] m) {
  for (int j = 0; j < m[0].length; j++) { // iterates over the columns
    for (int i = 0; i < m.length; i++)    // iterates over the elements of col j
      System.out.print(m[i][j] + " ");    // prints the element
    System.out.println();                 // end of the column
  }
}

Also in this case, we use two nested for loops: the outermost loop iterates over the columns (using control variable j), while the innermost loop iterates over the elements of column i (using control variable j). At the end of each column, a newline character is printed out.

Example of usage:

public static void main(String[] args) {
  short[][] A = {          // creates a matrix A of dimension 2x3
    { 1, 2, 2 },           // row 0 of A (array of 3 short)
    { 7, 5, 9 }            // row 1 of A (array of 3 short)
  };
  printMatrixRows(A);      // prints out the matrix row by row
  System.out.println();
  printMatrixColumns(A);   // prints out the matrix column by column
}

The program prints out the following:

1 2 2
7 5 9

1 7
2 5
2 9


next up previous
Next: Example: sum of two Up: Unit 07 Previous: Number of rows and