Java program to print the transpose of a matrix


The transpose of a matrix is the one whose rows are columns of the original matrix, i.e. if A and B are two matrices such that the rows of the matrix B are the columns of the matrix A then Matrix B is said to be the transpose of Matrix A.

To print the transpose of the given matrix −

  • Create an empty matrix.
  • Copy the contents of the original matrix to the new matrix such that elements in the [j][i] position of the original matrix should be copied to the [i][j] position of the new matrix.
  • Print the new matrix.

Example

Live Demo

public class TransposeSample{
   public static void main(String args[]){
      int a[][]={{1,2,3},{4,5,6},{7,8,9}};
      int b[][] = new int[3][3];
      System.out.println("Given matrix :: ");

      for(int i = 0;i<3;i++){
         for(int j = 0;j<3;j++){
            System.out.print(a[i][j]+" ");
         }
         System.out.println();
      }
      System.out.println("Matrix after transpose :: ");

      for(int i = 0;i<3;i++){
         for(int j = 0;j<3;j++){
            b[i][j] = 0;
            for(int k = 0;k<3;k++){
               b[i][j]=a[j][i];
            }
            System.out.print(b[i][j]+" ");
         }
         System.out.println();
      }
   }
}

Output

Given matrix ::
1 2 3
4 5 6
7 8 9
Matrix after transpose ::
1 4 7
2 5 8
3 6 9

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 13-Mar-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements