显示转置矩阵的Java程序
矩阵的转置是通过将行更改为列并将列更改为行来获得的。换句话说,A[][] 的转置是通过将 A[i][j] 更改为 A[j][i] 来获得的。
方法:
- 创建一个二维数组。
- 通过运行两个嵌套循环在数组中插入值。外部第 i 个循环将运行到行数,而内部第 jth 个循环将运行到列数。
- 为了显示矩阵的转置,运行与上述步骤相同的循环,但每次我们在循环内遍历时都打印第 a[j[i] 个元素。
例子:
Java
// Java Program to Display Transpose Matrix
import java.util.*;
public class GFG {
public static void main(String args[])
{
// initialize the array of 3*3 order
int[][] arr = new int[3][3];
System.out.println("enter the elements of matrix");
int k = 1;
// get the elements from user
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
arr[i][j] = k++;
}
}
System.out.println("Matrix before Transpose ");
// display original matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(" " + arr[i][j]);
}
System.out.println();
}
System.out.println("Matrix After Transpose ");
// transpose and print matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(" " + arr[j][i]);
}
System.out.println();
}
}
}
输出
enter the elements of matrix
Matrix before Transpose
1 2 3
4 5 6
7 8 9
Matrix After Transpose
1 4 7
2 5 8
3 6 9