Java program to find transpose of a matrix

Let’s learn java program to find transpose of a matrix.

Java program to find transpose of a matrix

Here in this java program user enters elements of a matrix. Transpose of a matrix can be performed by converting columns of matrix to row and rows of matrix to columns.

Let’s see java program to transpose a matrix,

import java.util.Scanner;

public class MatrixTransposeInJava 
{
   public static void main(String[] args) 
   { 
      int a, b;
      System.out.println("Please enter rows and columns : ");
      Scanner sc = new Scanner(System.in);
      int row = sc.nextInt();
      int col = sc.nextInt();
      int arrNum[][] = new int[row][col];
      System.out.println("Please enter matrix elements : ");
      for(a = 0; a < row; a++)
      {
         for(b = 0; b < col; b++) 
         {
            arrNum[a][b] = sc.nextInt();
         }
      }
      System.out.println("Before transpose : ");
      for(a = 0; a < row; a++)
      {
         for(b = 0; b < col; b++)
         {
            System.out.print(arrNum[a][b] + " ");
         }
         System.out.println(" ");
      }
      System.out.println("After transpose : ");
      for(a = 0; a < col; a++)
      {
         for(b = 0; b < row; b++)
         {
            System.out.print(arrNum[b][a] + " ");
         }
         System.out.println(" ");
      }
      sc.close();
   }
}



Output:

java program to find transpose of a matrix

Java program to display transpose matrix – another way

public class JavaTransposeMatrix 
{
public static void main(String[] args)
{
int arrInput[][] = {{2,4,6},{8,1,3},{5,7,9}};
int arrTranspose[][] = new int[3][3];
// transpose of a matrix
for(int a = 0; a < 3; a++)
{
for(int b = 0; b < 3; b++)
{
arrTranspose[a][b] = arrInput[b][a];
}
}
System.out.println("Before transpose : ");
for(int a = 0; a < 3; a++)
{
for(int b = 0; b < 3; b++)
{
System.out.print(arrInput[a][b] + " ");
}
System.out.println();
}
System.out.println("After transpose : ");
for(int a = 0; a < 3; a++)
{
for(int b = 0; b < 3; b++)
{
System.out.print(arrTranspose[a][b] + " ");
}
System.out.println();
}
}
}




Output:

Before transpose :
2 4 6
8 1 3
5 7 9
After transpose :
2 8 5
4 1 7
6 3 9


Also read – how to list all files in a directory in java