A matrix is a collection of numbers arranged into a fixed number of rows and columns. It is called a double dimensional array also.

The transpose of a matrix is a matrix where the row becomes columns and column becomes row.

Write a program to accept a double dimensional array (matrix) and print transpose of a matrix.

transpose of a matrix

To learn about how to take input in java watch the given video.
https://youtu.be/QZKcULOC4lg

import java.io.*;
public class Transarray
{
    int arr[][];
    int m,n;
    Transarray()
    {
        m=0;
        n=0;
    }
    Transarray(int mm,int nn)
    {
        m=mm;
        n=nn;
        arr=new int[mm][nn];
    }
    void fillarray()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("enter the elements of the array");
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                arr[i][j]=Integer.parseInt(br.readLine());
            }
        }
    }
    void transpose(Transarray a)
    {
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                this.arr[i][j]=a.arr[j][i];
            }
        }
    }

    void display()
    {
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                System.out.print(arr[i][j]);
            }
            System.out.println();
        }
    }
    public static void main()throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the order(size) of the array");
        int r=Integer.parseInt(br.readLine());
        int c=r;
        Transarray obj=new transarray(r,c);
        Transarray obj1=new transarray(r,c);
        obj.fillarray();
        obj.display();
        obj1.transpose(obj);
        System.out.println("The transpose of the array is:");
        obj1.display();
    }
}

Enter the order(size) of the array
3
Enter the elements of the array
1
2
3
4
5
6
7
8
9
1 2 3
4 5 6
7 8 9
The transpose of the array is:
1 4 7
2 5 8
3 6 9

To learn more about array click the given link
https://java4school.com/array

LEAVE A REPLY

Please enter your comment!
Please enter your name here