Given a matrix of custom size the task is to generate the transpose of original matrix.
To get the transpose of a matrix we either convert each row to column or convert each column to row.
Example: Consider a matrix
| 6 | 4 | 7 |
| 3 | 2 | 8 |
We will change the first row to first column.
| 6 | 4 | 7 |
→
| 6 |
| 4 |
| 7 |
Similarly change the second row to second column.
| 3 | 2 | 8 |
→
| 3 |
| 2 |
| 8 |
Hence we get transpose of original matrix as
| 6 | 3 |
| 4 | 2 |
| 7 | 8 |
Print the original matrix along with the transpose of the matrix.
Java
import java.util.*;
public class Transpose
{
public static void main(String args[])
{
int row=0,col=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter no.of rows: ");
row=sc.nextInt();
System.out.print("Enter no.of columns: ");
col=sc.nextInt();
int ar[][]=new int[row][col];
int tr[][]=new int[col][row];
System.out.println("Enter matrix elements:-");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
ar[i][j]=sc.nextInt();
}
}
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
tr[j][i]=ar[i][j];
}
}
System.out.println("Original Matrix:-");
for(int i=0;i<row;i++)
{
for(int j=0;j<col;j++)
{
System.out.print(ar[i][j]+"\t");
}
System.out.println();
}
System.out.println("Transpose Matrix:-");
for(int i=0;i<col;i++)
{
for(int j=0;j<row;j++)
{
System.out.print(tr[i][j]+"\t");
}
System.out.println();
}
}
}Java