create Matrix and transpose the matrix - Java Data Structure

Java examples for Data Structure:Matrix

Description

create Matrix and transpose the matrix

Demo Code


public class Main {
  public static void main(String args[]) throws Exception {
    int row = 4;//from w ww .j a va  2 s  .co m
    int col = 3;
    int[][] mMatrix = new int[row][col];
    int r, c;
    for (r = 0; r < mMatrix.length; r++) {
      for (c = 0; c < mMatrix[r].length; c++) {
        mMatrix[r][c] = r +c;
      }
    }
    // printing input Matrix :
    for (r = 0; r < mMatrix.length; r++) {
      for (c = 0; c < mMatrix[r].length; c++) {
        System.out.print(mMatrix[r][c]);
      }
      System.out.println();
    }

    // transpose matrix declared
    int[][] mTranpose = new int[row][col];
    for (r = 0; r < mMatrix.length; r++) {
      for (c = 0; c < mMatrix[r].length; c++) {
        mTranpose[c][r] = mMatrix[r][c];
      }

    }

    System.out.println("Transpose :");
    for (r = 0; r < mMatrix.length; r++) {
      for (c = 0; c < mMatrix[r].length; c++) {
        System.out.print(mTranpose[r][c]);
        if (c >= 0 && c < mMatrix[r].length - 1) {
          System.out.print(" ");

        }
      }
      System.out.println();
    }

  }
}

Related Tutorials