Java Program to Find Transpose of a Matrix

In this Java program, you’ll learn how to Find Transpose of a Matrix using the Java programming language

How to Find Transpose of a Matrix using JAVA? 

Example 1: 

RUN CODE SNIPPET
public class Main { 
    public static void main(String[] args) { 
        int row = 2, column = 3; 
        int[][] matrix = { {1, 2, 3}, {4, 5, 6} }; 
        display(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(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:  
1    2    3     
4    5    6     
The matrix is:  
1    4     
2    5     
3    6

For the transposed matrix we want to change the order of the matrix to 3*2, so we have transpose = int[column][row]. 

To transpose the matrix, we use transpose[j][i] = matrix[i][j]; by swapping the columns into row. 

Share:

Leave A Reply

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

You May Also Like

In this Java program, we will learn how to find the GCD of two numbers using Java.  GCD (Greatest Common...
  • Java
  • December 3, 2024
In this Java Program, you’ll learn how to swap two numbers using the Java programming language.  How to Swap Two...
  • Java
  • December 2, 2024
In this Java program , we will learn how to Find Largest Element in an Array in your Java program.   How to Find Largest Element...
  • Java
  • December 2, 2024