Reverse Matrix Elements Java Program | ISC Computer Science 2019 Theory

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

Example:

723715
126426
512394

becomes

271735
216624
532149

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): reverse 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.util.Scanner;
class MatRev{
    int ar[][];
    int m;
    int n;
    public MatRev(int mm, int nn){
        m = mm;
        n = nn;
        ar = 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++){
                ar[i][j] = Integer.parseInt(in.nextLine());
            }
        }
    }
    public int reverse(int x){
        int rev = 0;
        while(x != 0){
            rev = rev * 10 + x % 10;
            x /= 10;
        }
        return rev;
    }
    public void revMat(MatRev P){
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                this.ar[i][j] = reverse(P.ar[i][j]);
            }
        }
    }
    public void show(){
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                System.out.print(ar[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 rows = Integer.parseInt(in.nextLine());
        System.out.print("Number of columns: ");
        int cols = Integer.parseInt(in.nextLine());
        MatRev obj1 = new MatRev(rows, cols);
        obj1.fillarray();
        MatRev obj2 = new MatRev(rows, cols);
        obj2.revMat(obj1);
        System.out.println("Original Matrix:");
        obj1.show();
        System.out.println("Matrix with reversed elements:");
        obj2.show();
    }
}

Leave a Reply

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