Transpose of a matrix in java

Java Program to display transpose of a matrix

In the following question, we are supposed to enter a 2D array or rather Matrix. The 2D-array will be a dynamic array of size (R*C). After entering into the array, we’ll have to print the transpose matrix and along with the original matrix.

The basic idea to be kept in mind is:
Transpose of a Matrix is defined as a Matrix where the original Row elements becomes the column elements and Column elements becomes the Row Elements.

The standard algorithm will be:

  1. Enter the size of the 2D-array.
  2. Create the matrix of the input size.
  3. Using a loop construct, enter integer inputs in the matrix.
  4. Declare another matrix that will store the Transpose of the original matrix. The size will be same as original matrix.
  5. Using loop construct, swap the elements of original into transpose matrix such that the row becomes column index and vice versa.
  6. After the loop terminates, print the result accordingly.

Java Code:

/* Program to enter a 2D matrix and print the transpose of the matrix */

import java.util.*; class Transpose { public static void main() { Scanner inp = new Scanner(System.in);

System.out.print("\n Enter Row Size: "); //Entering Dimensions int r = inp.nextInt(); System.out.print("\n Enter Column Size: "); int c = inp.nextInt();

int i, j; int arr[][] = new int[r][c]; //Creating N-size Array int t[][] = new int[r][c]; for (i = 0; i < r; i++) //Entering N numbers in array { for (j = 0; j < c; j++) { System.out.print("\n Enter: "); arr[i][j] = inp.nextInt(); } }

for (i = 0; i < r; i++) //Transposing { for (j = 0; j < c; j++) { t[j][i] = arr[i][j]; } }

System.out.println("\n Original Matrix: "); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { System.out.print(arr[i][j] + " "); //Printing Original matrix } System.out.println(); }

System.out.println("\n Transpose Matrix: "); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { System.out.print(t[i][j] + " "); //Printing Transpose matrix by reversing Original } System.out.println(); }

} }

Output:

Enter Row Size: 3

Enter Column Size: 3

Enter: 1

Enter: 2

Enter: 3

Enter: 4

Enter: 5

Enter: 6

Enter: 7

Enter: 8

Enter: 9

Original Matrix: 1 2 3 4 5 6 7 8 9

Transpose Matrix: 1 4 7 2 5 8 3 6 9

Transpose of a matrix in java