In this tutorial we will learn how to transpose a matrix giving by the user using JAVA. We will also learn about the algorithm and code to transpose the matrix.
A transpose matrix is obtained by interchanging the rows into columns and columns into rows of the original matrix. In the language of coding the transpose of a matrix can be determined by Matrix[rows][columns]=matrix=[columns][rows].
Let us understand more clearly by the following example

1. Take the input from the user for number of rows and number of columns of the original matrix.
2. Store the matrix given by the user in a 2D array.
3. Now declare another 2D array variable to store the transpose matrix.
4. Transpose the matrix by following block of code
int transpose[][]=new int[10][10]; //Declaring transpose matrix variable
for(int i=0;i<rows;i++) //Transpose Matrix initialization
{
for(int j=0;j<columns;j++)
{
transpose[j][i]=matrix[i][j]; //Storing elements in the transpose matrix
}
}
5. Print the original matrix and the transposed matrix.
Below is our Java code:
/*JAVA program to tranpose the user given matrix*/
import java.util.*;
public class transpose_matrix
{
public static void main(String []args)
{
Scanner y=new Scanner(System.in); //Taking user input
int rows,columns; //Declaring variables
System.out.println("Enter the number of rows: \n");
rows=y.nextInt(); //Taking input for number of rows from user
System.out.println("Enter the number of column: \n");
columns=y.nextInt(); //Taking input for number of columns from user
int matrix[][]=new int[10][10]; //Declaring size of Matrix
System.out.println("Enter the elements of the matrix: ");
for(int i=0;i<rows;i++) //Initializing matrix
{
for(int j=0;j<columns;j++)
{
matrix[i][j]=y.nextInt();
}
}
System.out.println("The elements in the original matrix are: "); //Printing Original Matrix
for(int i=0;i<rows;i++)
{
for(int j=0;j<columns;j++)
{
System.out.print(matrix[i][j]+" ");
}
System.out.println("");
}
int transpose[][]=new int[10][10]; //Declaring transpose matrix variable
for(int i=0;i<rows;i++) //Transpose Matrix initialization
{
for(int j=0;j<columns;j++)
{
transpose[j][i]=matrix[i][j]; //Storing elements in the transpose matrix
}
}
System.out.println("After transposing the elements are...");
for(int i=0;i<rows;i++) //Printing the transpose matrix
{
for(int j=0;j<columns;j++)
{
System.out.print(transpose[i][j]+" ");
}
System.out.println("");
}
}
}


Submitted by Aryan Pradhan (aryanpradhan01)
Download packets of source code on Coders Packet
Comments