Prashnikaप्रश्निका
Code
About
‹ All Computer Science notes

ISC Practicals and Theory - Matrix Addition and Subtraction (OOP)

Updated 21 Oct 2026

Matrix addition and subtraction work on two matrices of the same order. In this version the class MatrixAddSub gets the order through a parameterised constructor, which creates both arrays; main reads the order, checks it and then creates the object. The result is the sum A + B and the difference A - B printed in neat rows.

Definition

Two matrices can be added or subtracted only when both have the same number of rows and columns. For matrices of order $m \times n$ the result is also $m \times n$, and each element is found from the matching elements:

S[i][j] = A[i][j] + B[i][j] and D[i][j] = A[i][j] - B[i][j]

Algorithm

  1. In main, read the rows r and columns c once, because both matrices have the same order.
  2. If either is outside 1 to 10, print Invalid size and stop.
  3. Otherwise create the object obj with new MatrixAddSub(r, c). The constructor stores the order in m and n and creates the arrays a[m][n] and b[m][n].
  4. Call obj.input(sc), which reads the elements of A and then of B with nested loops. The Scanner is passed in so that the same Scanner that read the order is used.
  5. Call add(), which adds a[i][j] + b[i][j] for every i and j and returns the sum matrix.
  6. Call subtract(), which finds a[i][j] - b[i][j] in the same way and returns the difference matrix.
  7. Call display() once for each result; it prints a heading and then the matrix row by row.

Program

The constructor creates the arrays, input() fills them, add() and subtract() each return a new matrix, and display() prints the matrix passed to it.

import java.util.Scanner;

/* Class MatrixAddSub stores two matrices A and B of the same order m x n
   and displays their sum A + B and their difference A - B. */
public class MatrixAddSub
{
    int m;              // number of rows of both matrices
    int n;              // number of columns of both matrices
    int a[][];          // stores the elements of matrix A
    int b[][];          // stores the elements of matrix B

    /* Parameterised constructor: stores the order and creates both arrays.
       Parameters: r is the number of rows, c is the number of columns. */
    MatrixAddSub(int r, int c)
    {
        m = r;
        n = c;
        a = new int[m][n];
        b = new int[m][n];
    }

    /* Reads the elements of A and B from the Scanner passed in.
       Parameter: sc is the Scanner connected to the keyboard. */
    void input(Scanner sc)
    {
        System.out.println("Enter the elements of matrix A:");
        for (int i = 0; i < m; i++)         // i moves over the rows
        {
            for (int j = 0; j < n; j++)     // j moves over the columns
            {
                a[i][j] = sc.nextInt();
            }
        }
        System.out.println("Enter the elements of matrix B:");
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                b[i][j] = sc.nextInt();
            }
        }
    }

    /* Adds the matching elements of A and B.
       Returns the sum matrix of order m x n. */
    int[][] add()
    {
        int s[][] = new int[m][n];          // the sum matrix
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                s[i][j] = a[i][j] + b[i][j];
            }
        }
        return s;
    }

    /* Subtracts each element of B from the matching element of A.
       Returns the difference matrix of order m x n. */
    int[][] subtract()
    {
        int d[][] = new int[m][n];          // the difference matrix
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                d[i][j] = a[i][j] - b[i][j];
            }
        }
        return d;
    }

    /* Prints a heading and then the matrix x row by row.
       Parameters: x is the matrix to print, heading is the line printed before it. */
    void display(int x[][], String heading)
    {
        System.out.println(heading);
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                System.out.print(x[i][j] + "\t");
            }
            System.out.println();           // new line after each row
        }
    }

    /* main reads the order, checks it, then creates the object and calls the methods. */
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows and columns (1 to 10): ");
        int r = sc.nextInt();               // rows typed by the user
        int c = sc.nextInt();               // columns typed by the user
        if (r >= 1 && r <= 10 && c >= 1 && c <= 10)
        {
            MatrixAddSub obj = new MatrixAddSub(r, c);
            obj.input(sc);
            obj.display(obj.add(), "Sum A + B:");
            obj.display(obj.subtract(), "Difference A - B:");
        }
        else
        {
            System.out.println("Invalid size");
        }
    }
}

Variable description table

VariableData TypePurpose
mintNumber of rows of both matrices (data member)
nintNumber of columns of both matrices (data member)
aint[][]Stores the elements of matrix A (data member)
bint[][]Stores the elements of matrix B (data member)
rintRows typed by the user in main; also the constructor parameter that receives the number of rows
cintColumns typed by the user in main; also the constructor parameter that receives the number of columns
scScannerReads the order in main; also the parameter of input() that carries the Scanner
iintLoop counter that moves over the rows
jintLoop counter that moves over the columns
sint[][]Local array in add() that stores the sum matrix
dint[][]Local array in subtract() that stores the difference matrix
xint[][]Parameter of display(): the matrix to be printed
headingStringParameter of display(): the line printed before the matrix
argsString[]Command line arguments of main; not used
objMatrixAddSubObject created in main to call the methods

Sample input and output

Sample 1

Enter the number of rows and columns (1 to 10): 2 3
Enter the elements of matrix A:
1 2 3
4 5 6
Enter the elements of matrix B:
6 5 4
3 2 1
Sum A + B:
7	7	7	
7	7	7	
Difference A - B:
-5	-3	-1	
1	3	5	

Sample 2

Enter the number of rows and columns (1 to 10): 1 1
Enter the elements of matrix A:
-5
Enter the elements of matrix B:
7
Sum A + B:
2	
Difference A - B:
-12	

Sample 3

Enter the number of rows and columns (1 to 10): 11 2
Invalid size

One value per line

Dry run

Take the first sample: r = 2, c = 3. The constructor sets m = 2, n = 3. A has rows 1 2 3 and 4 5 6, B has rows 6 5 4 and 3 2 1.

ija[i][j]b[i][j]s[i][j] = a + bd[i][j] = a - b
00167-5
01257-3
02347-1
104371
115273
126175

The sum matrix is 7 7 7 / 7 7 7 and the difference matrix is -5 -3 -1 / 1 3 5, the same as the first sample run.

Variations

  1. Scalar multiplication "Accept a matrix and an integer k and display the matrix multiplied by k."
  2. Different orders "Accept the orders of two matrices and display NOT POSSIBLE if they cannot be added."
  3. Diagonal sum "Display the sum matrix and the sum of its diagonal elements."