Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Java Program to Transpose Matrix

In this blog post, I am sharing how to find Transpose of given Matrix. Earlier, i have shared how to print prime number between 1 to 100 visit this program as well. It is an example for Two dimensional array in java.

The transpose of a matrix is defined as the matrix obtained by converting the rows as columns and columns as rows. Suppose we have matrix 3 rows and 4 columns. Its transpose matrix will have 4 rows and 3 columns.

Let me explain with the fallowing diagram:





 As shown in the above image the first matrix has 3x4 matrix that means 3 rows and 4 Columns,after Transpose of given matrix the result will be 4x3 matrix that means 4 rows and 3 columns like shown in picture.

In this program, To accept Input from the keyboard we are using Scanner class.

Scanner sc=new Scanner(System.in);

Now,whatever accepting int values from the keyboard for that i used sc.nextInt() method. This method accepts next integer value from the Scanner.Thus,by using this method in a loop,it is possible to accept all the integer values of the array from the keyboard.

Let us Write a Java Program to display Transpose of matrix

import java.io.*;
import java.util.Scanner;
class TransposeMatrix
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);//here i am using Scanner to accept data from the keyboard

System.out.println("enter rows,columns");//accept rows and columns of matrix
int row=sc.nextInt();
int col=sc.nextInt();

int arr[] []=new int[row][col];//creating an array with size[row][col]

System.out.println("enter a matrix");//accept a matrix from keyboard

for(int i=0;i
for(int j=0;j
arr[i][j]=sc.nextInt();
System.out.println("The transpose of Matrix:");

for(int i=0;i
{
for(int j=0;j
{
System.out.println(arr[j][i]+"   ");
}
System.out.println("\n");
}
}
}

Output:

Enter rows, columns
3  4
enter a matrix
1 2 3 4
5 6 7 8
9 1 2 3
The transpose of Matrix:

1 5 9
2 6 1
3 7 2
4 8 3

I hope you people enjoyed this post, for latest updates fallow me on google+ and share this post to your friends. You can also subscribe through your email to get latest updates.


This post first appeared on Learnprogramingbyluckysir, please read the originial post: here

Share the post

Java Program to Transpose Matrix

×

Subscribe to Learnprogramingbyluckysir

Get updates delivered right to your inbox!

Thank you for your subscription

×