Transpose of a matrix in java using BufferedReader

Let’s learn transpose of a matrix in java using BufferedReader.

Transpose of a matrix in java using BufferedReader

Here’s the transpose of a matrix using BufferedReader.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TransposeMatrixDemo 
{
   public static void main(String[] args) throws IOException 
   {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      System.out.print("Please enter number of rows: ");
      int row = Integer.parseInt(br.readLine());
      System.out.print("Please enter number of columns: ");
      int col = Integer.parseInt(br.readLine());
      int[][] arrMatrix = new int[row][col];
      int[][] arrTranspose = new int[row][col];
      System.out.println("Please enter elements of matrix: ");
      for(int a = 0; a < row; a++) 
      {
         for(int b = 0; b < col; b++) 
         {
            arrMatrix[a][b] = Integer.parseInt(br.readLine());
         }
      }
      System.out.println("Given Matrix\n");
      for(int a = 0; a < row; a++) 
      {
         for(int b = 0; b < col; b++) 
         {
            System.out.print(arrMatrix[a][b] + " ");
         }
         System.out.print("\n");
      }
      for(int a = 0; a < row; a++) 
      {
         for(int b = 0; b < col; b++) 
         {
            arrTranspose[b][a] = arrMatrix[a][b];
         }
      }
      System.out.println("Transpose matrix in java \n");
      for(int a = 0; a < col; a++) 
      {
         for(int b = 0; b < row; b++) 
         {
            System.out.print(arrTranspose[a][b] + " ");
         }
         System.out.print("\n");
      }
   }
}


Output:

Please enter number of rows: 3
Please enter number of columns: 3
Please enter elements of matrix:
1
2
3
4
5
6
7
8
9
Given Matrix

1 2 3
4 5 6
7 8 9
Transpose matrix in java

1 4 7
2 5 8
3 6 9


Also read – interface in java