Java Program to Display Transpose Matrix

«
»
This is a Java Program to Display Transpose Matrix.

Enter the elements of array as input. We obtain the transpose of given matrix by interchanging all the rows and columns of a matrix with the help of loops.

Here is the source code of the Java Program to Display Transpose Matrix. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

advertisement
  1. import java.util.Scanner;
  2. public class Transpose
  3. {
  4.     public static void main(String args[])  
  5.     {
  6. 	int i, j;
  7. 	System.out.println("Enter total rows and columns: ");
  8. 	Scanner s = new Scanner(System.in);
  9. 	int row = s.nextInt();
  10. 	int column = s.nextInt();
  11. 	int array[][] = new int[row][column];
  12. 	System.out.println("Enter matrix:");
  13.  	for(i = 0; i < row; i++)
  14.   	{
  15.    	    for(j = 0; j < column; j++) 
  16.      	    {
  17.         	array[i][j] = s.nextInt();
  18.         	System.out.print(" ");
  19.             }
  20.   	}
  21. 	System.out.println("The above matrix before Transpose is ");
  22.   	for(i = 0; i < row; i++)
  23.     	{
  24.       	    for(j = 0; j < column; j++)
  25.             {
  26.           	System.out.print(array[i][j]+" ");
  27.             }
  28.             System.out.println(" ");
  29.         }
  30.  	System.out.println("The above matrix after Transpose is ");
  31.   	for(i = 0; i < column; i++)
  32.     	{
  33.       	    for(j = 0; j < row; j++)
  34.             {
  35.                 System.out.print(array[j][i]+" ");
  36.             }
  37.             System.out.println(" ");
  38.         }
  39.     }
  40. }

Output:

$ javac Transpose.java
$ java Transpose
 
Enter total rows and columns: 
3 3
Enter matrix:
1
2
3
4
5
6
7
8
9
The above matrix before Transpose is 
1 2 3  
4 5 6  
7 8 9  
The above matrix after Transpose is 
1 4 7  
2 5 8  
3 6 9

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

advertisement
advertisement

Here’s the list of Best Reference Books in Java Programming, Data Structures and Algorithms.

Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
advertisement
advertisement
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn | Youtube | Instagram | Facebook | Twitter