Google News
logo
Java Program to find the Transpose of Matrix
In the following examples of Java program to find the transpose of a matrix :
Program :
public class TransposeMatrix {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] transpose = new int[matrix[0].length][matrix.length];
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[0].length; j++) {
                transpose[j][i] = matrix[i][j];
            }
        }
        printMatrix(transpose);
    }

    public static void printMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            for (int num : row) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }
}
Output :
1 4 7 
2 5 8 
3 6 9 
In this program, we have a matrix matrix represented as a two-dimensional array. We define a new matrix transpose to hold the transpose of the matrix.

We use two nested loops to iterate over the elements of the matrix. The outer loop iterates over the rows, and the inner loop iterates over the columns. For each element in the matrix, we assign it to the corresponding element in the transpose matrix by swapping the indices.

Finally, we print the transpose matrix to the console using a helper method printMatrix.