Java program to transpose a matrix.

Java Programming Java8Object Oriented Programming

Following is the required program.

Example

Live Demo

public class Tester {
   public static void main(String args[]) {
      int a[][] = { { 1, 3, 4 }, { 2, 4, 3 }, { 3, 4, 5 } };
      int t[][] = new int[3][3];
      // transpose the matrix
      for (int i = 0; i < 3; i++) {
         for (int j = 0; j < 3; j++) {
            t[i][j] = a[j][i];
         }
      }
      System.out.println("Original Matrix:");
      for (int i = 0; i < 3; i++) {
         for (int j = 0; j < 3; j++) {
            System.out.print(a[i][j] + " ");
         }
         System.out.println();
      }
      System.out.println("Transposed Matrix:");
      for (int i = 0; i < 3; i++) {
         for (int j = 0; j < 3; j++) {
            System.out.print(t[i][j] + " ");
         }
         System.out.println();
      }
   }
}

Output

Original Matrix:
1 3 4
2 4 3
3 4 5
Transposed Matrix:
1 2 3
3 4 4
4 3 5
raja
Published on 22-Apr-2018 21:07:56
Advertisements