Open In App

Java Program to Display Transpose Matrix

Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i].



Approach:

Example:






// Java Program to Display Transpose Matrix
  
import java.util.*;
public class GFG {
    public static void main(String args[])
    {
        // initialize the array of 3*3 order
        int[][] arr = new int[3][3];
  
        System.out.println("enter the elements of matrix");
  
        int k = 1;
  
        // get the elements from user
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                arr[i][j] = k++;
            }
        }
  
        System.out.println("Matrix before Transpose ");
  
        // display original matrix
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(" " + arr[i][j]);
            }
            System.out.println();
        }
  
        System.out.println("Matrix After Transpose ");
  
        // transpose and print matrix
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                System.out.print(" " + arr[j][i]);
            }
            System.out.println();
        }
    }
}

Output
enter the elements of matrix
Matrix before Transpose 
 1 2 3
 4 5 6
 7 8 9
Matrix After Transpose 
 1 4 7
 2 5 8
 3 6 9

Article Tags :