C++ Program to Multiply Two Matrices

  • Write a C++ program to multiply two matrices.
  • Algorithm for multiplication of two matrices.

In this program, we will multiply two matrices of size M X N and store the product matrix in another 2D array.


Points to Remember
Let A, B, and C be M X N matrices, and let 0 denote the M X N zero matrix.
  • Two matrices A(M X N) and B(P X Q) can be multiplied if and only if N is equal to P.
  • The product of two matrices A(M X N) and B(N X Q), denoted by A x B, is a matrix of dimension M × Q.
  • The time complexity of matrix multiplication program is O(n3).
  • Matrix Multiplication is not commutative : AB ≠ BA
  • Matrix Multiplication is Associative : (AB)C = A(BC)
  • Matrix Multiplication is Distributive : A(B+C) = AB + AC

C++ Program to Multiply Two Matrices

// C++ program to find sum of two matrix
#include <iostream>
using namespace std;
 
int main(){
    int rows1, cols1, rows2, cols2, i, j, k;
    int one[50][50], two[50][50], product[50][50];
    
    cout <<"Enter Rows and Columns of First Matrix\n";
    cin >> rows1 >> cols1;
     
    cout <<"Enter first Matrix of size "<<rows1<<" X "<<cols1;
    //  Input first matrix
    for(i = 0; i < rows1; i++){
        for(j = 0; j < cols1; j++){
            cin >> one[i][j];
        }
    }
    
    cout <<"Enter Rows and Columns of Second Matrix\n";
    cin >> rows2 >> cols2;
    
    if(cols1 != rows2){
        printf("Matrices cannot be multiplied\n");
        return 0;
 }
    //  Input second matrix
    cout <<"\nEnter second Matrix of size "<<rows2<<" X "<<cols2;
    for(i = 0; i < rows2; i++){
        for(j = 0; j < cols2; j++){
            cin >> two[i][j];
        }
    }

    for(i = 0; i < rows1; i++) {
        for(j = 0; j < cols2; j++) {
            for(k = 0; k < cols1; k++) {
                product[i][j] += one[i][k]*two[k][j];
            }
        }
    }
     
    cout <<"Product Matrix\n";
    for(i = 0; i < rows1; i++){
        for(j = 0; j < cols2; j++){
            cout << product[i][j] << " ";
        }
        cout << "\n";
    }

    return 0;
}
Output
Enter Rows and Columns of First Matrix
3 3
Enter first Matrix of size 3 X 3
1 2 3
4 5 6
7 8 9
Enter Rows and Columns of Second Matrix
3 3
Enter second Matrix of size 3 X 3
1 0 1
0 1 1
1 1 1
Product Matrix
4 5 6
10 11 15
16 17 24

In above program, we first ask user to enter the dimensions of first input matrix and store it in variable rows1 and cols1. The dimensions of matrices must be less than 50X50. Then one by one, using two for loops we take input for first input matrix.

Then we ask user to enter the dimension of second input matrix. It then checks whether column of first matrix is equal to row of second matrix. If not then it prints "Matrices cannot be multiplied" error message on screen.

Then we multiply two input matrices as per the algorithm mentioned here.