Java program to print the transpose of a matrix

Java Programming Java8Object Oriented Programming

Complete Java Programming Fundamentals With Sample Projects

98 Lectures 7.5 hours

C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

C++ Programming

238 Lectures 56.5 hours

The transpose of a matrix is the one whose rows are columns of the original matrix, i.e. if A and B are two matrices such that the rows of the matrix B are the columns of the matrix A then Matrix B is said to be the transpose of Matrix A.

To print the transpose of the given matrix −

• Create an empty matrix.
• Copy the contents of the original matrix to the new matrix such that elements in the [j][i] position of the original matrix should be copied to the [i][j] position of the new matrix.
• Print the new matrix.

Example

Live Demo

public class TransposeSample{
public static void main(String args[]){
int a[][]={{1,2,3},{4,5,6},{7,8,9}};
int b[][] = new int[3][3];
System.out.println("Given matrix :: ");

for(int i = 0;i<3;i++){
for(int j = 0;j<3;j++){
System.out.print(a[i][j]+" ");
}
System.out.println();
}
System.out.println("Matrix after transpose :: ");

for(int i = 0;i<3;i++){
for(int j = 0;j<3;j++){
b[i][j] = 0;
for(int k = 0;k<3;k++){
b[i][j]=a[j][i];
}
System.out.print(b[i][j]+" ");
}
System.out.println();
}
}
}

Output

Given matrix ::
1 2 3
4 5 6
7 8 9
Matrix after transpose ::
1 4 7
2 5 8
3 6 9
Updated on 13-Mar-2020 06:16:50