In this tutorial, we will write a program to calculate the Transpose of a matrix in Java. As this program is based on Array and uses of for loop so you may go through the following first.
Transpose of a matrix refers to converting the rows of a matrix into columns and columns of a matrix into rows. Consider a matrix A of 2 * 3
dimension, after transpose of A, the A matrix becomes 3 * 2
dimension.
The Program takes the input for both the column and row elements from the user using the scanner class and transposes for that matrix is calculated. And lastly displays the final result with altered rows and columns.
Java Program to Find the Transpose of a Matrix
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | //transpose of a matrix in java import java.util.Scanner; public class TransposeOfMatrix { public static void main(String args[]) { int row, col, i, j; Scanner in = new Scanner(System.in); System.out.println("Enter the rows and columns of the matrix"); row = in.nextInt(); col = in.nextInt(); int matrix[][] = new int[row][col]; System.out.println("Enter the elements of matrix"); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { matrix[i][j] = in.nextInt(); } } int transpose[][] = new int[col][row]; for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { transpose[j][i] = matrix[i][j]; } } System.out.println("Transpose of a entered matrix are:"); for (i = 0; i < col; i++) { for (j = 0; j < row; j++) { System.out.print(transpose[i][j]+"\t"); } System.out.print("\n"); } } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Enter the rows and columns of the matrix 2 3 Enter the elements of matrix 1 2 3 4 5 6 Transpose of a entered matrix are: 1 4 2 5 3 6 |