Matrix Difference ISC Computer Science 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(int, int), 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.util.Scanner;
class Matrix{
    int arr[][];
    int m;
    int n;
    public Matrix(int mm, int nn){
        if(mm > 25)
            m = 25;
        if(nn > 25)
            n = 25;
        m = mm;
        n = nn;
        arr = new int[m][n];
    }
    public void fillArray(){
        Scanner in = new Scanner(System.in);
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                arr[i][j] = Integer.parseInt(in.nextLine());
            }
        }
    }
    public Matrix subMat(Matrix a){
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                a.arr[i][j] -= this.arr[i][j];
            }
        }
        return a;
    }
    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) {
        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());
        Matrix x = new Matrix(r, c);
        System.out.println("Enter Matrix A elements:");
        x.fillArray();
        Matrix y = new Matrix(r, c);
        System.out.println("Enter Matrix B elements:");
        y.fillArray();
        System.out.println("Matrix A:");
        x.display();
        System.out.println("Matrix B:");
        y.display();
        x = y.subMat(x); //x = x - y
        System.out.println("Matrix A - B:");
        x.display();
    }
}

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