Write a Java program to transpose of a matrix.
07-04-2019    141 times

### Write a Java program to transpose of a matrix.

Read a matrix as a 2D array. Transpose of a matrix means convert all the rows into columns. Here we look the index of col and row are equal for the diagonal elements of the array. and also after transpose the diagonal elements are remain unchanged. Therefore, here we just exchanged the row elements with col elements with respect to the diagonal elements.


import java.util.*;

class MatrixTranspose
{
public static void main()
{
int arr1[3][3],i,j,temp;
Scanner sc=new Scanner(System.in);
System.out.println("Enter The Matrix Elements\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
arr1[i][j]=sc.nextInt();
}
}

for(i=0;i<3;i++)
{
for(j=i+1;j<3;j++)
{
temp=arr1[i][j];
arr1[i][j]=arr1[j][i];
arr1[j][i]=temp;
}
}

System.out.println("\nFinal array Elements\n");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(arr3[i][j] + "  ");
}
System.out.println("");
}
}
}