Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to display the Transpose of Matrix .

Java Code Example — Array Programs

ADVERTISEMENT

Java Program to display the Transpose of Matrix .

Objective

Write a Java program to display the transpose of a matrix.

Algorithm / Approach

  1. Declare a 3x2 matrix m1 and a 2x3 matrix trans (the dimensions must be swapped).
  2. Use nested loops to read input into m1[i][j].
  3. Inside the same loop, assign the value to the transposed matrix with swapped indices: trans[j][i] = m1[i][j].
  4. Use a new set of nested loops (iterating 2 rows and 3 columns) to print the trans matrix.
Matrix.java
import java.util.Scanner;
class Matrix {
 void transpose() {
  Scanner s=new Scanner(System.in);
  int m1[][] = new int[3][2];
  int trans[][] = new int[2][3];
  System.out.println("Enter Elements of Mat1: ");
  for(int i = 0; i< 3; i++) {
   for(int j = 0; j< 2; j++) { 
    m1[i][j] = s.nextInt();
    trans[j][i] = m1[i][j];
   }
  }
  System.out.println("Transpose of the matrix: ");
  for(int i = 0; i< 2; i++) {
   for(int j = 0; j< 3; j++) { 
    System.out.print(trans[i][j]+"  ");
   }
   System.out.println();
  }
 }
 public static void main(String[] a)
 {
  Matrix m = new Matrix();
  m.transpose();
 }
}

Expected Output

Enter Elements of Mat1:
1 2
3 4
5 6
Transpose of the matrix:
1  3  5
2  4  6

Explanation of the Program

  • The transpose of a matrix is formed by turning all the rows of a given matrix into columns and vice-versa.
  • If the original matrix has dimensions R x C, the transposed matrix will have dimensions C x R.
  • In code, this simply means whatever value was stored at index [row][col] is moved to index [col][row].

Complexity

Time Complexity O(r * c)
Space Complexity O(r * c) - For storing the newly shaped matrix.
ADVERTISEMENT