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

ISC Practicals and Theory - Matrix Class with Object Passing (OOP)

Updated 21 Oct 2026

In this version of matrix addition the class Matrix has a parameterised constructor Matrix(int r, int c) and the method add(Matrix m) **returns a new Matrix object** holding the sum: one object goes in as the parameter and a new object comes out.

Definition

Two matrices can be added only if they have the same order. The sum has that order and sum[i][j] = a[i][j] + b[i][j]. For example, rows $1\ 2$ and $3\ 4$ added to rows $5\ 6$ and $7\ 8$ give rows $6\ 8$ and $10\ 12$.

Algorithm

  1. main reads rows and cols. If either is less than 1 or more than 10, it prints the invalid order message and stops.
  2. Otherwise main creates a = new Matrix(rows, cols) and b = new Matrix(rows, cols). The constructor stores the order and creates the array data.
  3. a.accept("A") and b.accept("B") read the elements row by row with two nested loops.
  4. a.add(b) is called:
    • the method creates a new object sum of the same order;
    • for every i and j it stores data[i][j] + m.data[i][j] in sum.data[i][j];
    • it returns sum, which main keeps in s.
  5. s.display() prints the sum, one row per line.

Program

The object a on which add() is called supplies data[i][j]; the object b passed in is m and supplies m.data[i][j]. Neither is changed, because the result goes into a new object.

import java.util.Scanner;

/**
 * Class Matrix stores an r x c matrix of integers. OOP version:
 * parameterised constructor, and add(m) RETURNS a new Matrix object
 * holding the sum of the current object and the object passed in.
 */
public class Matrix
{
    int data[][];   // the elements of the matrix
    int r;          // number of rows
    int c;          // number of columns

    /**
     * Parameterised constructor: sets the order and makes space for the elements.
     * Parameters: r - number of rows; c - number of columns.
     */
    Matrix(int r, int c)
    {
        this.r = r;
        this.c = c;
        data = new int[r][c];
    }

    /**
     * Reads the elements of this matrix row by row.
     * Parameter: name - label shown in the prompt.
     */
    void accept(String name)
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter " + (r * c) + " elements of matrix " + name + " row by row:");
        for (int i = 0; i < r; i++)         // each row
        {
            for (int j = 0; j < c; j++)     // each column of that row
            {
                data[i][j] = sc.nextInt();
            }
        }
    }

    /**
     * Adds this matrix and the matrix m (same order).
     * Parameter: m - the Matrix object to be added.
     * Returns: a new Matrix object holding the sum.
     */
    Matrix add(Matrix m)
    {
        Matrix sum = new Matrix(r, c);   // new object for the result
        for (int i = 0; i < r; i++)
        {
            for (int j = 0; j < c; j++)
            {
                sum.data[i][j] = data[i][j] + m.data[i][j];   // add matching elements
            }
        }
        return sum;
    }

    /**
     * Displays the matrix, one row per line.
     */
    void display()
    {
        for (int i = 0; i < r; i++)
        {
            for (int j = 0; j < c; j++)
            {
                System.out.print(data[i][j] + "\t");
            }
            System.out.println();   // next row on a new line
        }
    }

    /**
     * Reads and checks the order, creates the Matrix objects and prints the sum.
     */
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows (r): ");
        int rows = sc.nextInt();       // rows of both matrices
        System.out.print("Enter the number of columns (c): ");
        int cols = sc.nextInt();       // columns of both matrices
        if (rows < 1 || rows > 10 || cols < 1 || cols > 10)
        {
            System.out.println("Invalid order. Rows and columns must be from 1 to 10.");
        }
        else
        {
            Matrix a = new Matrix(rows, cols);   // first matrix
            Matrix b = new Matrix(rows, cols);   // second matrix
            a.accept("A");
            b.accept("B");
            Matrix s = a.add(b);                 // object passed in, new object returned
            System.out.println("Sum of the matrices:");
            s.display();
        }
    }
}

Variable description table

VariableData TypePurpose
dataint[][]Data member: the elements of the matrix
rintData member: number of rows (also the constructor parameter)
cintData member: number of columns (also the constructor parameter)
nameStringParameter of accept(): label of the matrix shown in the prompt
scScannerReads the order and the elements typed by the user
mMatrixParameter of add(): the matrix to be added
sumMatrixNew object created in add() to hold the result
iintLoop counter for the row index
jintLoop counter for the column index
rowsintNumber of rows read in main
colsintNumber of columns read in main
aMatrixFirst matrix object in main
bMatrixSecond matrix object in main
sMatrixObject returned by add(): the sum
argsString[]Command-line arguments of main (not used)

Sample input and output

Sample 1

Enter the number of rows (r): 2
Enter the number of columns (c): 2
Enter 4 elements of matrix A row by row:
1 2
3 4
Enter 4 elements of matrix B row by row:
5 6
7 8
Sum of the matrices:
6	8	
10	12	

Sample 2

Enter the number of rows (r): 1
Enter the number of columns (c): 1
Enter 1 elements of matrix A row by row:
-5
Enter 1 elements of matrix B row by row:
5
Sum of the matrices:
0	

Sample 3

Enter the number of rows (r): 2
Enter the number of columns (c): 3
Enter 6 elements of matrix A row by row:
-1 0 4
2 -3 6
Enter 6 elements of matrix B row by row:
1 1 -4
-2 3 0
Sum of the matrices:
0	1	0	
0	0	6	

Sample 4

Enter the number of rows (r): 11
Enter the number of columns (c): 2
Invalid order. Rows and columns must be from 1 to 10.

One value per line

Dry run

Take the input $2 \times 3$ with $A$ = rows $-1\ 0\ 4$ and $2\ -3\ 6$, and $B$ = rows $1\ 1\ -4$ and $-2\ 3\ 0$. Each step of a.add(b) is:

ijdata[i][j]m.data[i][j]sum.data[i][j]
00-110
01011
024-40
102-20
11-330
12606

add() returns sum, and display() prints rows 0 1 0 and 0 0 6, as in the third sample run.

Variations

  1. Subtraction "Write a program using object passing to find the difference of two matrices."
  2. Multiplication "Write a program to multiply two Matrix objects, where the columns of the first equal the rows of the second."