Java transpose two dimension matrix

Posted on Updated on

 

Java program for transposing matrix. 
Transpose matrix changes rows into columns and columns into rows.
This program transposes two dimension array and transposed elements are stored in another two dimension array.

 

class transpose
{
int array [][] = {{10,20,30},{40,50,60},{70,80,90}};
int arrTrans [][];

public void showArray()
{
for(int i=0;i<3;i++)
{ 
for(int j=0;j<3;j++) 
{ 
System.out.print(array[i][j] + " "); 
} 
System.out.println();}
} 
public void showTrans()
{
for(int i=0;i<3;i++)
{ 
for(int j=0;j<3;j++) 
{ 
System.out.print(arrTrans [i][j] + " "); 
} 
System.out.println();
}
} 
public void transposeArray()
{
arrTrans = new int[3][3];

for(int i=0;i<3;i++)
{ 
for(int j=0;j<3;j++) 
{             
arrTrans[i][j] = array[j][i]; 
} 
System.out.println();

}

} 

}

 

public class transDemo
{

public static void main(String args[])
{

transpose obj = new transpose();

System.out.println(" Before transpose ");
obj.showArray();

obj.transposeArray();

System.out.println(" After transpose ");
obj.showTrans();

}

}

Output

Transpose