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

ISC Practicals and Theory - Matrix Multiplication (Using a Class)

Updated 20 Oct 2026

Matrix multiplication combines two two-dimensional arrays into a third one. In this version the work is divided among the methods of the class MatrixMult, and main only creates an object and calls them in order.

Definition

Two matrices $A$ and $B$ can be multiplied only when the number of columns of $A$ is equal to the number of rows of $B$. If $A$ has $m$ rows and $n$ columns, and $B$ has $p$ rows and $q$ columns, the product exists only when $n = p$. The product $C$ then has $m$ rows and $q$ columns.

Each element is the sum of products of one row of $A$ with one column of $B$:

C[i][j] = A[i][0] * B[0][j] + A[i][1] * B[1][j] + ... + A[i][n-1] * B[n-1][j]

If $A$ is $2 \times 3$ and $B$ is $3 \times 2$, then $C$ is $2 \times 2$. If $A$ is $2 \times 3$ and $B$ is $2 \times 2$, multiplication is not possible because $3 \ne 2$.

Algorithm

  1. In main, read the rows and columns of matrix A (r1, c1) and of matrix B (r2, c2).
  2. Create the object obj. The constructor MatrixMult(int, int, int, int) copies them into the data members m, n, p and q.
  3. Call isValid(). It returns true only if all four sizes are greater than zero. If it returns false, print Invalid size and stop.
  4. Call canMultiply(). It returns true when n == p. If it returns false, print Multiplication is not possible and stop.
  5. Call readMatrices(sc). It creates the arrays a, b and c and reads the elements of a and b with nested loops.
  6. Call multiply():
    • The loop i runs over the rows of A and the loop j over the columns of B.
    • c[i][j] is set to 0, then the loop k from 0 to n - 1 adds a[i][k] * b[k][j] to it.
  7. Call display() to print the product row by row.

Program

The constructor stores the sizes, isValid() and canMultiply() check them, readMatrices() reads both matrices, multiply() finds the product and display() prints it.

import java.util.Scanner;
public class MatrixMult
{
    int a[][], b[][], c[][];
    int m, n, p, q;

    MatrixMult(int r1, int c1, int r2, int c2)
    {
        m = r1;
        n = c1;
        p = r2;
        q = c2;
    }

    boolean isValid()
    {
        return m > 0 && n > 0 && p > 0 && q > 0;
    }

    boolean canMultiply()
    {
        return n == p;
    }

    void readMatrices(Scanner sc)
    {
        a = new int[m][n];
        b = new int[p][q];
        c = new int[m][q];
        System.out.println("Enter the elements of matrix A:");
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                a[i][j] = sc.nextInt();
            }
        }
        System.out.println("Enter the elements of matrix B:");
        for (int i = 0; i < p; i++)
        {
            for (int j = 0; j < q; j++)
            {
                b[i][j] = sc.nextInt();
            }
        }
    }

    void multiply()
    {
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < q; j++)
            {
                c[i][j] = 0;
                for (int k = 0; k < n; k++)
                {
                    c[i][j] = c[i][j] + a[i][k] * b[k][j];
                }
            }
        }
    }

    void display()
    {
        System.out.println("Product matrix:");
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < q; j++)
            {
                System.out.print(c[i][j] + "\t");
            }
            System.out.println();
        }
    }

    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter rows and columns of matrix A: ");
        int r1 = sc.nextInt();
        int c1 = sc.nextInt();
        System.out.print("Enter rows and columns of matrix B: ");
        int r2 = sc.nextInt();
        int c2 = sc.nextInt();
        MatrixMult obj = new MatrixMult(r1, c1, r2, c2);
        if (!obj.isValid())
        {
            System.out.println("Invalid size");
        }
        else if (!obj.canMultiply())
        {
            System.out.println("Multiplication is not possible");
        }
        else
        {
            obj.readMatrices(sc);
            obj.multiply();
            obj.display();
        }
    }
}

Variable description table

VariableData TypePurpose
aint[][]Data member that stores the elements of matrix A
bint[][]Data member that stores the elements of matrix B
cint[][]Data member that stores the elements of the product matrix
mintData member: number of rows of matrix A
nintData member: number of columns of matrix A
pintData member: number of rows of matrix B
qintData member: number of columns of matrix B
r1intNumber of rows of A, read in main and passed to the constructor
c1intNumber of columns of A, read in main and passed to the constructor
r2intNumber of rows of B, read in main and passed to the constructor
c2intNumber of columns of B, read in main and passed to the constructor
scScannerReads the sizes and the elements from the keyboard
iintLoop counter for the rows
jintLoop counter for the columns
kintLoop counter that runs along a row of A and a column of B
argsString[]Command line arguments of main; not used
objMatrixMultObject created in main to call the methods

Sample input and output

Sample 1

Enter rows and columns of matrix A: 2 3
Enter rows and columns of matrix B: 3 2
Enter the elements of matrix A:
1 2 3
4 5 6
Enter the elements of matrix B:
7 8
9 10
11 12
Product matrix:
58	64	
139	154	

Sample 2

Enter rows and columns of matrix A: 2 3
Enter rows and columns of matrix B: 2 2
Multiplication is not possible

Sample 3

Enter rows and columns of matrix A: 0 3
Enter rows and columns of matrix B: 3 2
Invalid size

One value per line

Dry run

Take $A$ as $2 \times 3$ with rows 1 2 3 and 4 5 6, and $B$ as $3 \times 2$ with rows 7 8, 9 10 and 11 12. The constructor sets m = 2, n = 3, p = 3, q = 2. isValid() returns true and canMultiply() returns true because n == p. Then multiply() works as follows.

ijkWorkingc[i][j]
0000 + 1 x 77
0017 + 2 x 925
00225 + 3 x 1158
0100 + 1 x 88
0118 + 2 x 1028
01228 + 3 x 1264
1000 + 4 x 728
10128 + 5 x 973
10273 + 6 x 11139
1100 + 4 x 832
11132 + 5 x 1082
11282 + 6 x 12154

display() prints the rows 58 64 and 139 154, the same as the first sample run.

Exam tip: Keep each method to one job: checking, reading, multiplying and displaying are separate methods, and main only creates the object and calls them.

Variations

  1. Square matrices "Accept two square matrices of size n x n, where n is greater than 1 and less than 10, and display their product."
  2. Transpose "Write a method to find the transpose of a matrix and display it."
  3. Diagonal sum "Display the product matrix and the sum of its diagonal elements."