C++ Program to multiply two Matrices

One can define matrices in C++ using 2-D arrays.

In this post I will assume, that you are familiar with the concepts of arrays.

In this post I will show you how to write a C++ program that gives the product of two matrices.

The product of two matrices isn’t always defined.
The product of matrices A and B :
A\times B is defined only when the no. of columns of A is equal to the no. of rows in matrix B .

If A is an m\times p matrix, and B is an p\times n matrix, then the product matrix would be a m\times n matrix,
(A\times B)_{ij} = \sum_{k=1}^pA_{ik}B_{kj}

With the above, information, we can proceed to write a simple program, to multiply two matrices of given sizes.
We would also need to check whether the matrix product is defined or not.

The program is pretty much self-explanatory.

PROGRAM:

//Matrix Multiply
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
	int m,n,p,q;
	
	a:cout<<"\nEnter the order of the matrix A:\n";
	cin>>m;
	cin>>n;
	cout<<"\nEnter the order of the matrix B:\n";
	cin>>q;
	cin>>p;
	if(n!=q){
		cout<<"\nCan't multiply!\nThe number of columns of A should be equal to the number of rows in B.\n\nPlease enter again!\n\n";
		goto a;
	}
	double a[m][n];
	double b[n][p];
	double prod[m][p];
	cout<<"\nEnter the elements of the matrix A row-wise:\n";
    for (int i=0;i<m;i++)
        for (int j=0;j<n;j++)    
            cin>>a[i][j];  
            
    cout<<"\nEnter the elements of the matrix B row-wise:\n";
    for (int i=0;i<n;i++)
        for (int j=0;j<p;j++)    
            cin>>b[i][j];  
	
	
	for (int i=0;i<m;i++){
		for (int j=0;j<p;j++){
			prod[i][j]=0;
			for(int k=0;k<n;k++){
				prod[i][j]=prod[i][j]+a[i][k]*b[k][j];
			}
		}
	}
	cout<<"\nThe product AxB is:\n";
	for (int i=0;i<m;i++){
        for (int j=0;j<p;j++){
        	cout<<prod[i][j]<<setw(16);
		}
        cout<<"\n";
    }   
    return 0;
}

OUTPUT:

Sample output

I'm a physicist specializing in theoretical, computational and experimental condensed matter physics. I like to develop Physics related apps and softwares from time to time. Can code in most of the popular languages. Like to share my knowledge in Physics and applications using this Blog and a YouTube channel.



Leave a Reply

Your email address will not be published. Required fields are marked *