Transpose of Matrix Java

Question – Write a Program to find the transpose of a square matrix of size N*N. Transpose of a matrix is obtained by changing rows to columns and columns to rows.

Logic – Interchange transpose matrix, rows and columns

  • Iterate through each row and column of the matrix.
  • Swap the element of ith row, jth column with the element at jth row, ith column.

Let’s solve the problem with the below example

Example
N = 4
mat[][] = {{1, 1, 1, 1},
           {2, 2, 2, 2}
           {3, 3, 3, 3}
           {4, 4, 4, 4}}
Output: 
{{1, 2, 3, 4},  
 {1, 2, 3, 4}  
 {1, 2, 3, 4}
 {1, 2, 3, 4}}

Method to transpose a matrix

public static void transpose(int n,int a[][])
    {
        int track=0;
        while(track<n){
            for(int i=track+1;i<n;i++){
                int temp=a[track][i];
                a[track][i]=a[i][track];
                a[i][track]=temp;
            }
            track++;
        }
    }

Transpose of a matrix with the primary method

public class TransposeMatrix {
    public static void main(String[] args) {
        int mat[][] = {{1, 1, 1, 1},
                {2, 2, 2, 2},
                {3, 3, 3, 3},
                {4, 4, 4, 4}};
        int n=4;
        
        //calling transpose method
        transpose(n,mat);
        
        //printing elements of transpose row by row
        for(int i=0;i<n;i++){
            System.out.println("Row->"+i);
            for(int j=0;j<n;j++){
                System.out.print(mat[i][j]+" ");
            }
            System.out.println();
        }
    }
    public static void transpose(int n,int a[][])
    {
        int track=0;
        while(track<n){
            for(int i=track+1;i<n;i++){
                int temp=a[track][i];
                a[track][i]=a[i][track];
                a[i][track]=temp;
            }
            track++;
        }
    }
}

Main Method Output

See also  Find Perfect Number in Java

Row->0
1 2 3 4
Row->1
1 2 3 4
Row->2
1 2 3 4
Row->3
1 2 3 4

Leave a Reply

Your email address will not be published. Required fields are marked *

WhatsApp Icon Join For Job Alerts