Find Transpose of a Matrix in Java language
Find transpose of a matrix in java language in java language. In this program, you will learn how to find transpose of a matrix in java language.
The transpose of a matrix in linear algebra is an operator that flips a matrix over its diagonal. This switches the rows and columns indices of matrix A by producing another matrix.
Source Code
// Find Transpose of a Matrix in Java language
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int r, c, i, j;
// r - this is the matrix's rows
// c - this is the matrix's columns
System.out.println("-----Enter the number of rows & columns of the matrix-----");
r = in.nextInt();
c = in.nextInt();
int a[][], t[][];
a = new int[r][c];
t = new int[c][r];
// a - this is the input matrix
// t - this is the transpose matrix
System.out.println("\n-----Enter the matrix's elements-----");
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
System.out.print("Enter element at position[" + (i + 1) + (j + 1) + "]: ");
a[i][j] = in.nextInt();
}
System.out.print("\n");
}
// It will display the input matrix
System.out.println("\n-----The entered matrix-----");
for (i = 0; i < r; ++i) {
System.out.print("\t");
for (j = 0; j < c; ++j) {
System.out.print(a[i][j] + "\t");
if (j == c - 1)
System.out.print("\n");
}
System.out.print("\n");
}
// It will transposes matrix
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
t[j][i] = a[i][j];
}
}
// It will display the transposed matrix
System.out.println("\n-----The transpose of the matrix-----");
for (i = 0; i < c; ++i) {
System.out.print("\t");
for (j = 0; j < r; ++j) {
System.out.print(t[i][j] + "\t");
if (j == r - 1)
System.out.print("\n");
}
System.out.print("\n");
}
}
}
Output
-----Enter the number of rows & columns of the matrix-----
3
4
-----Enter the matrix's elements-----
Enter element at position[11]: 12
Enter element at position[12]: 34
Enter element at position[13]: 54
Enter element at position[14]: 23
Enter element at position[21]: 56
Enter element at position[22]: 23
Enter element at position[23]: 65
Enter element at position[24]: 44
Enter element at position[31]: 23
Enter element at position[32]: 75
Enter element at position[33]: 23
Enter element at position[34]: 76
-----The entered matrix-----
12 34 54 23
56 23 65 44
23 75 23 76
-----The transpose of the matrix-----
12 56 23
34 23 75
54 65 23
23 44 76