1import java.util.Scanner;
2public class MatrixTransposeInJava
3{
4 public static void main(String[] args)
5 {
6 int[][] arrGiven = {{2,4,6},{8,1,3},{5,7,9}};
7 // another matrix to store transpose of matrix
8 int[][] arrTranspose = new int[3][3];
9 // transpose matrix code
10 for(int a = 0; a < 3; a++)
11 {
12 for(int b = 0; b < 3; b++)
13 {
14 arrTranspose[a][b] = arrGiven[b][a];
15 }
16 }
17 System.out.println("Before matrix transpose: ");
18 for(int a = 0; a < 3; a++)
19 {
20 for(int b = 0; b < 3; b++)
21 {
22 System.out.print(arrGiven[a][b] + " ");
23 }
24 System.out.println();
25 }
26 System.out.println("After matrix transpose: ");
27 for(int a = 0; a < 3; a++)
28 {
29 for(int b = 0; b < 3; b++)
30 {
31 System.out.print(arrTranspose[a][b] + " ");
32 }
33 System.out.println();
34 }
35 }
36}
1 //Transpose a Matrix
2
3 for (int row = 0; row < matrix.length; row++) {
4
5 for (int col = row; row < matrix[row].length; col++)
6 {
7 // Swap
8 int data = matrix[row][col];
9 matrix[row][col] = matrix[col][row];
10 matrix[col][row] = data;
11 }
12
13 }
1// transpose of a matrix in java without using second matrix
2import java.util.Scanner;
3public class WithoutSecondMatrix
4{
5 public static void main(String[] args)
6 {
7 Scanner sc = new Scanner(System.in);
8 int a, b, row, column, temp;
9 System.out.println("Please enter number of rows: ");
10 row = sc.nextInt();
11 System.out.println("Please enter the number of columns: ");
12 column = sc.nextInt();
13 int[][] matrix = new int[row][column];
14 System.out.println("Please enter elements of matrix: ");
15 for(a = 0; a < row; a++)
16 {
17 for(b = 0; b < column; b++)
18 {
19 matrix[a][b] = sc.nextInt();
20 }
21 }
22 System.out.println("Elements of the matrix: ");
23 for(a = 0; a < row; a++)
24 {
25 for(b = 0; b < column; b++)
26 {
27 System.out.print(matrix[a][b] + "\t");
28 }
29 System.out.println("");
30 }
31 // transpose of a matrix
32 for(a = 0; a < row; a++)
33 {
34 for(b = 0; b < a; b++)
35 {
36 temp = matrix[a][b];
37 matrix[a][b] = matrix[b][a];
38 matrix[b][a] = temp;
39 }
40 }
41 System.out.println("transpose of a matrix without using second matrix: ");
42 for(a = 0; a < row; a++)
43 {
44 for(b = 0; b < column; b++)
45 {
46 System.out.print(matrix[a][b] + "\t");
47 }
48 System.out.println("");
49 }
50 sc.close();
51 }
52}
1for (int row = 0; row < matrix.length; row++) {
2
3 for (int col = row; col < matrix[row].length; col++)
4 {
5 // Swap
6 int data = matrix[row][col];
7 matrix[row][col] = matrix[col][row];
8 matrix[col][row] = data;
9 }
10
11 }