Java Program to find Matrix Transpose
You are Here:
Find Matrix Transpose
In the following example, we will transpose the given matrix (two-dimensional array).
Example
Java Compiler
public class myClass
{
public static void main(String[] args)
{
int i, j, n;
int[][] arr = {
{1, 1, 1},
{2, 2, 2},
{3, 3, 3}
};
System.out.println("Matrix (3 x 3):");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
System.out.format("%d ", arr[i][j]);
System.out.println();
}
for(i=0; i<3; i++)
{
for(j=i+1; j<3; j++)
{
n = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = n;
}
}
System.out.println("\nMatrix Transpose:");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
System.out.format("%d ", arr[i][j]);
System.out.println();
}
}
}
Output
Matrix (3 x 3):
1 1 1
2 2 2
3 3 3
Matrix Transpose:
1 2 3
1 2 3
1 2 3
In the following example, we will get the values for (3 x 3) Matrix from the user and display the transpose matrix.
Example
Java Compiler
import java.util.Scanner;
public class myClass
{
public static void main(String[] args)
{
int i, j, n;
int[][] arr = new int[3][3];
Scanner reader = new Scanner(System.in);
System.out.println("Enter Matrix (3 x 3):");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
arr[i][j] = reader.nextInt();
}
for(i=0; i<3; i++)
{
for(j=i+1; j<3; j++)
{
n = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = n;
}
}
System.out.println("\nMatrix Transpose:");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
System.out.format("%d ", arr[i][j]);
System.out.println();
}
}
}
Output
Enter Matrix (3 x 3):
2 2 2
4 4 4
6 6 6
Matrix Transpose:
2 4 6
2 4 6
2 4 6
Reminder
Hi Developers, we almost covered 90% of String functions and Interview Question on Java with examples for quick and easy learning.
We are working to cover every Single Concept in Java.
Please do google search for:
Join Our Channel
Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.
This channel is primarily useful for Full Stack Web Developer.