
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print the Transpose of a Matrix in Java
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
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
Advertisements