Matrix Transpose in Java

In this article, we are going to write A java program to create a transpose matrix of a given matrix. First, we will take a matrix ( any size) input from the user using the Scanner class after that we generate the transpose matrix.

Matrix Transpose

Transpose of a matrix is created by converting a row into column and column into row . An example is given below where a normal matrix and the transpose of that matrix is shown.

matrix transpose

Matrix Transpose in Java

Steps

  • First take matrix input from user using Java Scanner class
  • Create matrix transpose by converting row into column and column into row (check login in the given code – transpose.java)
  • Print the result

Matrix Transpose Java Code

matrixTranspose.java

The given code is able to generate transpose of any size matrix because instead of predefine matrix we are taking matrix input with the help of Scanner.

package learn;
import java.util.Scanner;


// Wap for generating transpose of given matrix

public class matrixTranspose {
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter the number of rows");
		int row=sc.nextInt();
		
		System.out.println("Enter the number of column");
		int column=sc.nextInt();
		
		int[][] matrix = new int[row][column];
		
		System.out.println("Enter the matrix");
		for(int i=0;i<row;i++) {
			for(int j=0;j<column;j++) {
				matrix[i][j]=sc.nextInt();
			}
		}
		
		
		int[][] transpose = new int[column][row];
		
		// Matrix Transpose Logic
		for(int i=0;i<row;i++) {
			for(int j=0;j<column;j++) {
				transpose[j][i]=matrix[i][j];
			}
		}
		
		System.out.println("\nGiven Matrix ");
		matrixPrint (matrix,row,column);
		
		System.out.println("\nTranspose of given matrix");
		matrixPrint(transpose,column,row);
		
		}
	
	
	// Method for printing Matrix
	
	   public static void matrixPrint(int[][] matrix,int row,int column) {
		for(int i=0;i<row;i++) {
			for(int j=0;j<column;j++) {
				System.out.print( matrix[i][j]+" ");
			}
			System.out.println();
		}
	}

}

Output Matrix Transpose in Java

matrix transpose in java

Similar Tutorials

Multidimensional Array in Java – https://gangforcode.com/multidimensional-array-in-java/
Matrix Addition in Java – https://gangforcode.com/matrix-addition-in-java/ matrix multiplication – https://gangforcode.com/matrix-multiplicatin/

Leave a Comment