Reverse Matrix Elements ISC 2019 Theory

Design a class MatRev to reverse each element of a matrix.

Example:

72   371  5
12 6 426
5 123 94

becomes

27   173  5
21 6 624
5 321 49

Some of the members of the class are given below:

Class name: MatRev
Data members/instance variables:
arr[][]: to store integer elements
m: to store the number of rows
n: to store the number of columns
Member functions/methods:
MatRev(int mm, int nn): parameterized constructor to initialize the data members m = mm and n = nn.
void fillArray(): to enter elements in the array.
int reverse(int x): returns the reverse of the number x.
void revMat(MatRev p): reverses each element of the array of the parameterized object and stores it in the array of the current object.
void show(): displays the array elements in matrix form.

Define the class MatRev giving details of the constructor, void fillArray(), int reverse(int), void revMat(MatRev) and void show(). Define the main() function to create objects and call the functions accordingly to enable the task.

import java.io.*;
class MatRev{
    private int arr[][];
    private int m;
    private int n;
    public MatRev(int mm, int nn){
        m = mm;
        n = nn;
        arr = new int[m][n];
    }
    public void fillArray()throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(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(br.readLine());
            }
        }
    }
    public int reverse(int x){
        int rev = 0;
        for(int i = x; i != 0; i /= 10)
            rev = rev * 10 + i % 10;
        return rev;
    }
    public void revMat(MatRev p){
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                this.arr[i][j] = reverse(p.arr[i][j]);
            }
        }
    }
    public void show(){
        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[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter number of rows: ");
        int x = Integer.parseInt(br.readLine());
        System.out.print("Enter number of columns: ");
        int y = Integer.parseInt(br.readLine());
        MatRev obj1 = new MatRev(x, y);
        MatRev obj2 = new MatRev(x, y);
        obj1.fillArray();
        obj2.revMat(obj1);
        System.out.println("Original Matrix");
        obj1.show();
        System.out.println("Matrix with reversed elements");
        obj2.show();
    }
}

Leave a Reply