SUNDAY, 12 JULY 2026
Guide For School logo Guide For SchoolStudy Guide For Students On Java Programming
Physics | Chemistry | Mathematics
ICSE | ISC | CBSE
Guide For School logo Guide For SchoolICSE and ISC Resources

Matrix Multiplication Program in Java and Python

13 February 2015

Matrix multiplication program with algorithm, explanation, Java solution and simple Python solution for ICSE and ISC students.

Question:

Write a program to input two matrices and multiply them. Matrix multiplication is possible only when the number of columns of the first matrix is equal to the number of rows of the second matrix.

Matrix multiplication example showing compatible rows and columns
Matrix multiplication uses each row of the first matrix with each column of the second matrix.
INPUT: Rows of 1st Matrix: 2 Columns of 1st Matrix: 3 Rows of 2nd Matrix: 3 Columns of 2nd Matrix: 2 First Matrix: 8 1 2 -5 6 7 Second Matrix: -5 1 0 2 -11 7 OUTPUT: The Result of Multiplication is: -62 24 -52 56

Algorithm:

Step 1: Start.

Step 2: Accept row and column counts for both matrices.

Step 3: Check whether columns of the first matrix equal rows of the second matrix.

Step 4: If the condition fails, display that multiplication is not possible and stop.

Step 5: Declare the first matrix A, second matrix B and result matrix C.

Step 6: Input all elements of A using row-column nested loops.

Step 7: Input all elements of B using row-column nested loops.

Step 8: For every result position C[i][j], initialize a sum variable to 0.

Step 9: Run k from 0 to columns of A - 1 and add A[i][k] * B[k][j] to sum.

Step 10: Store the final sum in C[i][j].

Step 11: After all positions are calculated, display A, B and C.

Step 12: Stop.

Explanation:

The program first checks the order condition for matrix multiplication. If the first matrix has c1 columns and the second has r2 rows, multiplication is possible only when c1 == r2.

The result matrix has the number of rows of the first matrix and the number of columns of the second matrix. Therefore its size is r1 × c2.

Three loops are needed for multiplication. The outer two loops choose the result cell C[i][j], while the inner loop moves through the matching row of A and column of B.

For every value of k, the product A[i][k] * B[k][j] is added to a running sum. This sum becomes one element of the result matrix.

The sum variable must be reset to 0 for every new result cell. If it is not reset, values from earlier cells would incorrectly carry into the next calculation.

Matrix multiplication is based on row-column products. An element in the result matrix is formed by multiplying one row of the first matrix with one column of the second matrix and adding those products. This is why three nested loops are needed. The outer loops select the result position, and the innermost loop performs the summation over matching elements. The number of columns in the first matrix must match the number of rows in the second matrix; otherwise multiplication is not defined.

Java Program:

Java
/**
* The class MatrixMultiplication inputs 2 Matrices and performs Matrix Multiplication on them
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/

import java.util.*;
class MatrixMultiplication
{
    void printMatrix(int P[][], int r, int c) // Funtion for printing an array
    {
        for(int i=0; i<r; i++)
        {
            for(int j=0; j<c; j++)
            {
                System.out.print(P[i][j]+"\t");
            }
            System.out.println();
        }
    }

    public static void main(String args[])throws Exception
    {
        MatrixMultiplication ob = new MatrixMultiplication();
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter no. of rows of 1st Matrix : ");
        int r1=sc.nextInt();
        System.out.print("Enter no. of columns of 1st Matrix : ");
        int c1=sc.nextInt();

        System.out.print("Enter no. of rows of 2nd Matrix : ");
        int r2=sc.nextInt();
        System.out.print("Enter no. of columns of 2nd Matrix : ");
        int c2=sc.nextInt();

        if(c1 != r2) // Condition for Multiplication to be possible
        {
            System.out.println("Matrix Multiplication of the given order is not possible");
        }
        else
        {
            int A[][]=new int[r1][c1]; // Array to store 1st Matrix
            int B[][]=new int[r2][c2]; // Array to store 2nd Matrix
            int C[][]=new int[r1][c2]; // Array to store Result of Multiplication of 2 Matrices

            System.out.println("*************************");
            System.out.println("Inputting the 1st Matrix");
            System.out.println("*************************");
            for(int i=0; i<r1; i++)
            {
                for(int j=0; j<c1; j++)
                {
                    System.out.print("Enter an element : ");
                    A[i][j]=sc.nextInt();
                }
            }
            System.out.println("*************************");
            System.out.println("Inputting the 2nd Matrix");
            System.out.println("*************************");
            for(int i=0; i<r2; i++)
            {
                for(int j=0; j<c2; j++)
                {
                    System.out.print("Enter an element : ");
                    B[i][j]=sc.nextInt();
                }
            }

            /* Matrix Multiplication Starts Here */

            int sum = 0;
            for(int i=0; i<r1; i++)
            {
                for(int j=0; j<c2; j++)
                {
                    for(int k=0; k<c1; k++)
                    {
                        sum = sum + A[i][k]*B[k][j];
                    }
                    C[i][j]=sum;
                    sum=0;
                }
            }

            /* Printing all the Matrices */
            System.out.println("n*************************");
            System.out.println("          Output         ");
            System.out.println("*************************");
            System.out.println("The 1st Matrix is");
            ob.printMatrix(A,r1,c1);
            System.out.println("*************************");
            System.out.println("The 2nd Matrix is");
            ob.printMatrix(B,r2,c2);
            System.out.println("************************************");
            System.out.println("The Result of Multiplication is");
            ob.printMatrix(C,r1,c2);
        }
    }
}

Equivalent Python Program:

Python
# Read the matrix sizes and verify whether multiplication is possible.
r1 = int(input("Enter rows of 1st Matrix: "))
c1 = int(input("Enter columns of 1st Matrix: "))
r2 = int(input("Enter rows of 2nd Matrix: "))
c2 = int(input("Enter columns of 2nd Matrix: "))

if c1 != r2:
    print("Matrix multiplication is not possible")
else:
    A = []
    B = []

    # Input both matrices using nested loops for row and column positions.
    print("Enter elements of 1st Matrix:")
    for i in range(r1):
        row = []
        for j in range(c1):
            row.append(int(input()))
        A.append(row)

    print("Enter elements of 2nd Matrix:")
    for i in range(r2):
        row = []
        for j in range(c2):
            row.append(int(input()))
        B.append(row)

    C = []
    for i in range(r1):
        row = []
        for j in range(c2):
            total = 0
            # Multiply row i of A with column j of B.
            for k in range(c1):
                total = total + A[i][k] * B[k][j]
            row.append(total)
        C.append(row)

    print("The Result of Multiplication is:")
    for i in range(r1):
        for j in range(c2):
            print(C[i][j], end="	")
        print()

Output:

INPUT: Rows of 1st Matrix: 2 Columns of 1st Matrix: 3 Rows of 2nd Matrix: 3 Columns of 2nd Matrix: 2 First Matrix: 8 1 2 -5 6 7 Second Matrix: -5 1 0 2 -11 7 OUTPUT: The Result of Multiplication is: -62 24 -52 56

Leave a Reply

Your email address will not be published. Comments are reviewed before appearing publicly.

Send a comment or correction

Study smarter

Everything you need for ICSE and ISC Computer

Programs, revision notes, solved papers and practical guidance—organized for quick study.

Browse all resources →