## Sunday 15 September 2019

### Java Program to Transpose a Matrix

In the previous post, written code for matrix  multiplication, in the current post, we will a write a java code to transpose a given matrix. The transpose of matrix is to interchange the rows and columns for the given matrix.

Example:-
 Transpose of Matrix

The below code is the source code of java program to transpose of a given matrix,

MatrixTranspose.java,

```package com.example.demo;

public class MatrixTranspose {

public static void main(String[] args) {

int matrix[][] = {{1,2,3,4},{5,6,7,8},{9,10,11,12}};

int m = 3;    //no. of rows
int n = 4;    //no. of columns

System.out.println("Matrix before transpose is - ");```
```
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
System.out.print(matrix[i][j]+" ");
}
System.out.println(" ");
}

int transMatrix[][] = new int[n][m];

System.out.println("Matrix after transpose is - ");```
```
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
transMatrix[i][j] = matrix[j][i];
System.out.print(transMatrix[i][j]+" ");
}
System.out.println(" ");
}
}
}
```
Output:--
Matrix before transpose is -
1   2   3   4
5   6   7   8
9 10 11 12
Matrix after transpose is -
1 5  9
2 6 10
3 7 11
4 8 12

Related Posts:--
1) Java code to move all zero of an integer array to the end of the array
2) Java Program to Perform Matrix Multiplication
3) Write a Java program to print the Floyd's triangle
4) Java Code to Print the Numbers as Pyramid - Examples
5) Java Program to find the Missing Number in an Array
6) Java program to print the first n prime numbers
7) Swap two variables without using third variable in Java
8) Java program to find second largest number in an array
9) Sort a binary array using one traversal in Java
10) Difference between NoClassDefFoundError and ClassNotFoundException in Java