by Dinesh Thakur Category: array

Algorithm for Transpose of a Matrix:

step 1: read r, c

step 2: create an integer array a[][] of size r,c

step 3: create an integer array b[][] of size c,r

step 4: initialize i=0

step 5: repeat through step-10 while (i < r)

step 6: initialize j=0

step 7: repeat through step-9 while (j < c)

step 8: read a[i][j]

step 9: j=j+ 1

step 10: i=i+ 1

step 11: reset i=0

step 12: repeat through step-17 while (i < r)

step 13: reset j=0

step 14: repeat through step-16 while (j < c)

step 15: b[j][i]=a[i][j]

step 16: j=j+ 1

step 17: i=i+ 1

step 18: initialize i=0

step 19: repeat through step-25 while (i < c)

step 20: move to new line

step 21: initialize j=0

step 22: repeat through step-24 while (j < r)

step 23: print b[i][j]

step 24: j=j+ 1

step 25: i=i+ 1

step 26: Exit

 

Here is the Java Example for Transpose of a Matrix:

import java.util.Scanner;
class TransposeMatrix
{
            public static void main(String args[])
       {
            int i,j,t,r,c ;
            Scanner s1=new Scanner(System.in);
            System.out.print("Enter the size of Rows : ");
            r=s1.nextInt();
            System.out.println("Enter the size of Columns :");
            c=s1.nextInt();
            System.out.println("\nThe Elements into the Array:->");
            int a[][]=new int[r][c];
            int b[][]=new int[c][r];
            for(i=0;i<r;i++)
            for(j=0;j<c;j++)
            a[i][j]=s1.nextInt();
            System.out.println("\nThe elements of Array\n");
            for(i=0;i<r;i++)
                {
                   System.out.print("\n");
            for(j=0;j<c;j++)
                {
                   System.out.print(a[i][j]+"\t");
                }
                   for(i=0;i<r;i++)
                  {
                   for(j=0;j<c;j++)
                      {
                         b[j][i]=a[i][j];
                      }
                   }
            System.out.println("\nAfter Transfering print the data :->");
                    for(i=0;i<c;i++)
                       {
                          System.out.print("\n");
                          for(j=0;j<r;j++)
                              {
                                System.out.print(b[i][j]+"\t");
                               }
                        }
                    }
       }
}

Transpose of a Matrix in Java





About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Related Articles