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

ISC Practicals and Theory - Matrix Class with Object Passing

Updated 21 Oct 2026

A class Matrix can hold a two-dimensional array and its order as data members, and a method can receive other Matrix objects as parameters. This is the single-class version: a default constructor, accept() to read the elements, add(Matrix a, Matrix b) which stores the sum of two matrices in the current object, and display().

Definition

Two matrices can be added only if they have the same order (the same number of rows and columns). The sum $C = A + B$ has that same order and each element is the sum of the matching elements:

c[i][j] = a[i][j] + b[i][j]

For example, with $A$ having rows $1\ 2$ and $3\ 4$, and $B$ having rows $5\ 6$ and $7\ 8$, the sum has rows $6\ 8$ and $10\ 12$.

Algorithm

  1. main reads the number of rows rows and columns cols. If either is less than 1 or more than 10, it prints the invalid order message and stops.
  2. Otherwise main creates three objects a, b and s of the class Matrix. The default constructor sets r and c to 0.
  3. a.accept(rows, cols, "A") and b.accept(rows, cols, "B") each set the order, create the array data and read the elements row by row with two nested loops.
  4. s.add(a, b) is called with the two objects passed as parameters:
    • it copies the order from a into r and c of s and creates the array data;
    • for every i and j it stores a.data[i][j] + b.data[i][j] in data[i][j] of s.
  5. s.display() prints the sum, one row per line.

Program

Each method does one job. In add(), a and b are objects, so their elements are reached with a.data[i][j], and the result is stored in the object on which add() is called.

import java.util.Scanner;

/**
 * Class Matrix stores an r x c matrix of integers and adds two matrices.
 * Main version: default constructor, accept() reads the elements, and
 * add(a, b) stores the sum of the two Matrix objects in the current object.
 */
public class Matrix
{
    int data[][];   // the elements of the matrix
    int r;          // number of rows
    int c;          // number of columns

    /**
     * Default constructor: makes an empty matrix of order 0 x 0.
     */
    Matrix()
    {
        r = 0;
        c = 0;
        data = null;
    }

    /**
     * Sets the order of this matrix and reads its elements row by row.
     * Parameters: rows, cols - the order; name - label shown in the prompt.
     */
    void accept(int rows, int cols, String name)
    {
        Scanner sc = new Scanner(System.in);
        r = rows;
        c = cols;
        data = new int[r][c];   // space for r x c elements
        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();
            }
        }
    }

    /**
     * Stores in this matrix the sum of the matrices a and b (same order).
     * Parameters: a, b - the two Matrix objects to be added. Returns nothing.
     */
    void add(Matrix a, Matrix b)
    {
        r = a.r;
        c = a.c;
        data = new int[r][c];
        for (int i = 0; i < r; i++)
        {
            for (int j = 0; j < c; j++)
            {
                data[i][j] = a.data[i][j] + b.data[i][j];   // add matching elements
            }
        }
    }

    /**
     * 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();   // first matrix
            Matrix b = new Matrix();   // second matrix
            Matrix s = new Matrix();   // will hold the sum
            a.accept(rows, cols, "A");
            b.accept(rows, cols, "B");
            s.add(a, b);
            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
cintData member: number of columns
rowsintParameter of accept(), and the number of rows read in main
colsintParameter of accept(), and the number of columns read in main
nameStringParameter of accept(): label of the matrix shown in the prompt
scScannerReads the order and the elements typed by the user
aMatrixParameter of add() and the first matrix object in main
bMatrixParameter of add() and the second matrix object in main
sMatrixObject in main that holds the sum
iintLoop counter for the row index
jintLoop counter for the column index
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 2$ with $A$ = rows $1\ 2$ and $3\ 4$, and $B$ = rows $5\ 6$ and $7\ 8$. Each step of s.add(a, b) is:

ija.data[i][j]b.data[i][j]Statementdata of s after the step
0015data[0][0] = 1 + 5row 0: 6, -
0126data[0][1] = 2 + 6row 0: 6, 8
1037data[1][0] = 3 + 7row 1: 10, -
1148data[1][1] = 4 + 8row 1: 10, 12

display() prints rows 6 8 and 10 12, as in the first 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."
  3. Equality "Check whether two Matrix objects of the same order are equal."