✏️ Explanatory Question
Write a Java program that takes a 2D array of size 2x3 and returns its transpose.
1 2 3 4 5 6
Output:
1 4 2 5 3 6
Write a Java program that takes a 2D array of size 2x3 and returns its transpose.
1 2 3 4 5 6
Output:
1 4 2 5 3 6
public class Main {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
int[][] transpose = new int[3][2];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
transpose[j][i] = matrix[i][j];
}
}
// Print Transpose
for (int i = 0; i < transpose.length; i++) {
for (int j = 0; j < transpose[i].length; j++) {
System.out.print(transpose[i][j] + " ");
}
System.out.println();
}
}
}