Matrix Subtraction ISC 2013 Theory

A class Matrix contains a two-dimensional integer array of order [m × n]. The maximum value possible for both ‘m’ and ‘n’ is 25. Design a class Matrix to find the difference of the two matrices. The details of the members of the class are given below:

Class name: Matrix
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:
Matrix(int mm, int nn): to initialize the size of the matrix m = mm and n = nn.
void fillArray(): to enter the elements of the matrix.
Matrix subMat(Matrix a): Subtract the current object from the matrix of parameterized object and return the resulting object.
void display(): display the matrix elements.

Specify the class Matrix giving details of the constructor, void fillArray(), Matrix subMat(Matrix) and void display(). Define the main() function to create objects and call the methods accordingly to enable the task.

import java.io.*;
class Matrix{
    private int arr[][];
    private int m;
    private int n;
    public Matrix(int mm, int nn){
        m = mm;
        n = nn;
        if(m > 25)
            m = 25;
        if(n > 25)
            n = 25;
        arr = new int[m][n];
    }
    public void fillArray()throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                arr[i][j] = Integer.parseInt(br.readLine());
            }
        }
    }
    public Matrix subMat(Matrix a){
        Matrix temp = new Matrix(m, n);
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                temp.arr[i][j] = a.arr[i][j] - this.arr[i][j];
            }
        }
        return temp;
    }
    public void display(){
        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("Number of rows: ");
        int rows = Integer.parseInt(br.readLine());
        System.out.print("Number of columns: ");
        int columns = Integer.parseInt(br.readLine());
        Matrix obj1 = new Matrix(rows, columns);
        System.out.println("Enter matrix 1 elements:");
        obj1.fillArray();
        Matrix obj2 = new Matrix(rows, columns);
        System.out.println("Enter matrix 2 elements:");
        obj2.fillArray();
        Matrix obj3 = obj2.subMat(obj1);
        System.out.println("Matrix 1:");
        obj1.display();
        System.out.println("Matrix 2:");
        obj2.display();
        System.out.println("Difference:");
        obj3.display();
    }
}

Leave a Reply

%d bloggers like this: