Arrays

Java Program to Find Transpose of a Matrix

A Java program to find the transpose of a matrix.

Problem Description

Write a Java program to find the transpose of a matrix.

Code

TransposeMatrix.java
public class TransposeMatrix {
    public static void main(String[] args) {
        int row = 2, column = 3;
        int[][] matrix = { {2, 3, 4}, {5, 6, 4} };

        // Display current matrix
        display(matrix);

        // Transpose the matrix
        int[][] transpose = new int[column][row];
        for(int i = 0; i < row; i++) {
            for (int j = 0; j < column; j++) {
                transpose[j][i] = matrix[i][j];
            }
        }

        // Display transposed matrix
        display(transpose);
    }

    public static void display(int[][] matrix) {
        System.out.println("The matrix is: ");
        for(int[] row : matrix) {
            for (int column : row) {
                System.out.print(column + "    ");
            }
            System.out.println();
        }
    }
}

Output

The matrix is: 
2    3    4    
5    6    4    
The matrix is: 
2    5    
3    6    
4    4    

Explanation

  1. Transpose: Swapping rows and columns.
  2. Logic: transpose[j][i] = matrix[i][j].