public class TransposeMatrix {
public static void main(String[] args) {
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int[][] transpose = new int[matrix[0].length][matrix.length];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
transpose[j][i] = matrix[i][j];
}
}
printMatrix(transpose);
}
public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
}
1 4 7
2 5 8
3 6 9
matrix
represented as a two-dimensional array. We define a new matrix transpose
to hold the transpose of the matrix
.matrix
. The outer loop iterates over the rows, and the inner loop iterates over the columns. For each element in the matrix
, we assign it to the corresponding element in the transpose
matrix by swapping the indices.transpose matrix
to the console using a helper method printMatrix
.