Java program to print the transpose of a given matrix
KW.java
import java.util.Scanner;
class KW
{
    public static void main(String args[])
    {
        int i,j,m,n;
        Scanner sc=new Scanner(System.in);
        System.out.println("———————————————————————————————————————————");
        System.out.println("Program to find the transpose of a given matrix ");
        System.out.println("———————————————————————————————————————————");
        System.out.print("Enter the number of rows ");
        m=sc.nextInt();
        System.out.print("Enter the number of columns ");
        n=sc.nextInt();
        
        if(m<=0||n<=0||m*n<=0)
        {
            System.out.println("\nEnter the valid number of rows & columns");
        }
        else
        {
            if(m!=n)
            {
                System.out.println("\nGiven matrix is not a square matrix");
            }
            else
            {
                int matrix[][]=new int[m][n];
                System.out.println("Enter the elements of matrix ");
                for(i=0;i<m;i++)
                {
                    for(j=0;j<n;j++)
                    {
                        matrix[i][j]=sc.nextInt();
                    }
                }
                System.out.println("\nEntered matrix is ");
                for(i=0;i<m;i++)
                {
                    for(j=0;j<n;j++)
                    {
                        System.out.print("\t"+matrix[i][j]);
                    }   
                    System.out.println("\t");
                }
                System.out.println("\nTranspose of matrix is ");
                for(i=0;i<m;i++)
                {
                    for(j=0;j<n;j++)
                    {
                        System.out.print("\t"+matrix[j][i]);
                    }   
                    System.out.println("\t");
                }
            }
        }
        System.out.println("———————————————————————————————————————————");
    }
}
Output
kodingwindow@kw:~$ javac KW.java
kodingwindow@kw:~$ java KW ——————————————————————————————————————————— Program to find the transpose of a given matrix ——————————————————————————————————————————— Enter the number of rows 3 Enter the number of columns 3 Enter the elements of matrix 1 2 3 4 5 6 7 8 9 Entered matrix is 1 2 3 4 5 6 7 8 9 Transpose of matrix is 1 4 7 2 5 8 3 6 9 ——————————————————————————————————————————— kodingwindow@kw:~$
What Next?
Java Classes
Advertisement