Java program to perform transpose of a matrix

Hey guys!! Welcome to flower brackets blog. Today you will learn java program to perform transpose of a matrix.

java program to perform transpose of a matrix

Here in this java program user enters elements of a matrix.Transpose of a matrix can be obtained by interchanging all the rows and columns of matrix.

Also read – matrix multiplication java

Let’s see java program to display transpose 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 :

Please enter rows and columns :
3 3
Please enter matrix elements :
2 4 6 8 1 3 5 7 9
Before transpose :
2 4 6
8 1 3
5 7 9
After transpose :
2 8 5
4 1 7
6 3 9


Also read – matrix addition and subtraction in java

Related Posts