Matrix Transpose ISC Computer Science 2009 Theory

A transpose of an array is obtained by interchanging the elements of the rows and columns.

A class Transarray contains a two-dimensional integer array of order (m × n). The maximum value possible for both 'm' and 'n' is 20.

Design a class Transarray to find the transpose of a given matrix. The details of the members of the class are given below:

Class name: Transarray

Data members/instance variables:
arr[][]: stores the matrix elements
m: integer to store the number of rows
n: integer to store the number of columns

Member functions:
Transarray(): default constructor
Transarray(int row, int col): to initialize the size of the matrix as m = row, n = col
void fillArray(): to enter the elements of the matrix
void transpose(Transarray a): to find the transpose of a given matrix
void dispArray(): displays the array in a matrix form

Specify the class Transarray giving details of the constructors, void fillArray(), void transpose(Transarray) and void dispArray(). You need not write the main() function.

import java.util.Scanner;
class Transarray{
    int arr[][];
    int m;
    int n;
    public Transarray(){
        m = 0;
        n = 0;
        arr = null;
    }
    public Transarray(int row, int col){
        m = row;
        n = col;
        arr = new int[m][n];
    }
    public void fillArray(){
        Scanner in = new Scanner(System.in);
        System.out.println("Enter matrix elements:");
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                arr[i][j] = Integer.parseInt(in.nextLine());
            }
        }
    }
    public 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];
            }
        }
    }
    public void dispArray(){
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; 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("Number of rows: ");
        int r = Integer.parseInt(in.nextLine());
        System.out.print("Number of columns: ");
        int c = Integer.parseInt(in.nextLine());
        Transarray t1 = new Transarray(r, c);
        Transarray t2 = new Transarray(c, r);
        t1.fillArray();
        System.out.println("Original matrix:");
        t1.dispArray();
        t2.transpose(t1);
        System.out.println("Transposed matrix:");
        t2.dispArray();
    }
}

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory