Protected by Copyscape
Powered By Blogger

Thursday, February 13, 2020

How to transpose an array in Java?

The below code will help you to convert rows into columns and columns in to rows.



public class Transposing {


static int TArray[][]= {{1,2,3},{4,5,6},{7,8,9}};


public static int[][] transpose(int[][] arr)
{
if (arr==null||arr.length==0) {
return arr;}

int Rows=arr.length;
int Cols=arr[0].length;

int [][] arr_new=new int[Cols][Rows];

for(int x=0;x<Rows;x++)
{
for(int y=0;y<Cols;y++)
{
arr_new[y][x]=arr[x][y];
}
}
return arr_new;

}
public static void main(String[] args)
{


// TODO Auto-generated method stub
int i,j;

System.out.println("Before Transponse");

for(i=0;i<TArray.length;i++)
{
for(j=0;j<TArray[0].length;j++)
{
System.out.print(TArray[i][j]+"  ");
}
System.out.println();
}

System.out.println("After Transpose");
TArray=transpose(TArray);
for(i=0;i<TArray.length;i++)
{
for(j=0;j<TArray[0].length;j++)
{
System.out.print(TArray[i][j]+"  ");
}
System.out.println();
}
}

}



OUTPUT

Before Transponse
1  2  3  
4  5  6  
7  8  9  
After Transpose
1  4  7  
2  5  8  
3  6  9  


No comments: