Matrix Transpose Java Program | ISC Computer Science 2023 Paper 1

A class Trans is defined to find the transpose of a square matrix. A transpose of a matrix is obtained by interchanging the elements of the rows and columns.

Example: If size of the matrix = 3, then
ORIGINAL

1157
8139
1620

TRANSPOSE

1181
5136
7920

Some of the members of the class are given below:

Class name: Trans
Data members/instance variables:
arr[][]: to store integers in the matrix
m: integer to store the size of the matrix
Methods/Member functions:
Trans(int mm): parameterized constructor to initialize the data member m = mm
void fillarray(): to enter integer elements in the matrix
void transpose(): to create the transpose of the given matrix
void display(): displays the original matrix and the transposed matrix by invoking the method transpose()

Specify the class Trans giving details of the constructor(), void fillarray(), void transpose() and void display(). Define a main() function to create an object and call the functions accordingly to enable the task.

import java.util.Scanner;
class Trans{
    private int arr[][];
    private int m;
    public Trans(int mm){
        m = mm;
        arr = new int[m][m];
    }
    public void fillarray(){
        Scanner in = new Scanner(System.in);
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){
                arr[i][j] = Integer.parseInt(in.nextLine());
            }
        }
    }
    public void transpose(){
        int b[][] = new int[m][m];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){
                b[i][j] = arr[j][i];
            }
        }
        arr = b;
    }
    public void display(){
        for(int i = 0; i < m; i++){
            for(int j = 0; j < m; j++){
                System.out.print(arr[i][j] + "\t");
            }
            System.out.println();
        }
    }
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("Matrix size: ");
        int size = Integer.parseInt(in.nextLine());
        Trans obj = new Trans(size);
        obj.fillarray();
        System.out.println("ORIGINAL");
        obj.display();
        obj.transpose();
        System.out.println("TRANSPOSE");
        obj.display();
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *