Hello friends today we are going to execute matrix multiplication program in c++. Suppose we have two matrix A and B. To get multiplication of A and B we have to compare rows and columns. Suppose A is a*b matrix and B is m*n matrix then this two matrices should satisfy condition b=m and a=n. If it does not satisfy the condition then the matrix multiplication is not possible. Let me give you a example. If we have one matrix having 3 rows and 4 columns and another matrix with 4 rows and 3 columns then matrix multiplication is possible because it satisfy the above condition (first matrix’s columns=second matrix’s rows). so our goal is to check the condition before multiplication in c++ program.

Matrix multiplication program in c++

So here we go. we are going to multiply two matrix via c++ program.


Source code for matrix multiplication program in c++


#include<iostream.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k;
clrscr();
cout<<"Enter the row and coloums for first matrix"<<"n";
cin>>m>>n;
cout<<"Enter the row and coloums for second matrix"<<"n";
cin>>p>>q;

cout<<"First matrix value"<<"n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cin>>a[i][j];
}
}
cout<<"second mtrix value"<<"n";

for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
cin>>b[i][j];
}
}
if(n==p)
{
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<p;k++)
{
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
}
cout<<"Multiplication";
cout<<"n";
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
cout<<c[i][j]<<"t";
}
cout<<"n";
}
}
else
{
cout<<" It can not be multiplied";
}
getch();
}
#include<iostream.h>
#include<conio.h>
void main()
{
int a[5][5],b[5][5],c[5][5],m,n,p,q,i,j,k;
clrscr();
cout<<"Enter the row and coloums for first matrix"<<"n";
cin>>m>>n;
cout<<"Enter the row and coloums for second matrix"<<"n";
cin>>p>>q;

cout<<"First matrix value"<<"n";
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
{
cin>>a[i][j];
}
}
cout<<"second mtrix value"<<"n";

for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
{
cin>>b[i][j];
}
}
if(n==p)
{
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0;
for(k=0;k<p;k++)
{
c[i][j]=c[i][j]+(a[i][k]*b[k][j]);
}
}
}
cout<<"Multiplication";
cout<<"n";
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
cout<<c[i][j]<<"t";
}
cout<<"n";
}
}
else
{
cout<<" It can not be multiplied";
}
getch();
}

Output

Logic of matrix multiplication

First we decided rows and columns of two matrices and got the corresponding values for each matrix. Then we checked the condition for rows and columns. Then we simply initialized the resultant matrix with zero and turn by turn add the values with multiplication of elements of A and B with the help of k. Then we print the final result.

By jigar

Leave a Reply

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