Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
1.44/5 (2 votes)
See more:
I want to print transpose of a 2D array (matrix) . This code is printing the same array instead of the transposed matrix ? What mistake am I doing ?

 package assignment1;
    import java.util.* ;
    public class q11
    {
    public static void main (String argc[] )    
    {
    Scanner e = new Scanner (System.in) ;
    int m  , c=0 ;
    int n;     // finding transpose of a matrix .
    
    System.out.println(" enter number of rows ");
    m= e.nextInt() ; // rows
    System.out.println(" enter number of columns");
    n =e.nextInt() ;//columns

    int twod[][] = new int [m][n] ; // 2d array created .   

    System.out.println(" enter array elements ");
 
    for ( int i = 0 ; i<=m-1 ; i++ )
    {
    for (int j=0 ; j <= n-1 ; j++)
    {
    twod [i][j] = e.nextInt() ;
    }
    }
 
    System.out.println(" array is :");
 
    for ( int i = 0 ; i<=m-1 ; i++)
    {
    for (int j=0 ; j <= n-1 ; j++)
    {
    System.out.print(twod[i][j]+"  ");
    }
     System.out.println("");
    }  
    // transposing matrix .
    for (int i =0 ; i<= m-1 ; i++)
    {
     for (int j=0 ; j<= n -1 ; j++)
     {

    c=twod[j][i] ;
    twod[j][i] = twod[i][j] ;       
    twod[i][j] = c ;
  
     }
         }
 
    System.out.println(" transposed array is : ");
    for ( int i = 0 ; i<=m-1 ; i++)
    {
    for (int j=0 ; j <= n-1 ; j++)
    {
    System.out.print(twod[i][j]+"  ");
    }
     System.out.println("");
    }
 
 
}
        
        
        }


What I have tried:

I have tried to run it on Netbeans IDE .
Posted
Updated 27-Jan-17 8:45am

When the matrix is being transposed, that is , when the values are being exchanged using variable c then inner for loop must start with j=i+1 . If j is initially 0 then the swapped values will again be swapped , resulting in the same array . For example If we take m=2 , n=2 then it will print the same array .
 
Share this answer
 
The first problem of this code:
Java
// transposing matrix .
for (int i =0 ; i<= m-1 ; i++)
{
    for (int j=0 ; j<= n -1 ; j++)
    {

        c=twod[j][i] ;
        twod[j][i] = twod[i][j] ;
        twod[i][j] = c ;

    }
}

is that it transpose each element 2 times. You need to change the loops to scan only a half of the matrix (triangle) the swap is doing the other half.

Secondary problem, your code do not handled non square matrix.

You don't need to transpose the matrix to simply print it in transposed form.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900