Matrix Multiplication in C++

Share on facebook
Share on twitter
Share on linkedin
Share on twitter
Share on tumblr

In this Basic C++ Program, we will have a look at how to write a c++ program to write a program of Matrix multiplication in C++. 

We can add, subtract, multiply and divide 2 matrices. To do so, we are taking input from the user for row number, column number, first matrix elements, and second matrix elements. Then we are performing multiplication on the matrices entered by the user.

In matrix multiplication, the first matrix one-row element is multiplied by the second matrix all column elements.

Let’s try to understand the matrix multiplication of 3*3 and 3*3 matrices by the figure given below:

Matrix multiplication in C++.

#include <iostream>  

using namespace std;  

int main()  

{  

int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;    

cout<<"enter the number of row=";    

cin>>r;    

cout<<"enter the number of column=";    

cin>>c;    

cout<<"enter the first matrix element=\n";    

for(i=0;i<r;i++)    

{    

for(j=0;j<c;j++)    

{    

cin>>a[i][j];  

}    

}    

cout<<"enter the second matrix element=\n";    

for(i=0;i<r;i++)    

{    

for(j=0;j<c;j++)    

{    

cin>>b[i][j];    

}    

}    

cout<<"multiply of the matrix=\n";    

for(i=0;i<r;i++)    

{    

for(j=0;j<c;j++)    

{    

mul[i][j]=0;    

for(k=0;k<c;k++)    

{    

mul[i][j]+=a[i][k]*b[k][j];    

}    

}    

}    

//for printing result    

for(i=0;i<r;i++)    

{    

for(j=0;j<c;j++)    

{    

cout<<mul[i][j]<<" ";    

}    

cout<<"\n";    

}    

return 0;  

}    

OUTPUT:

enter the number of row=3  

enter the number of column=3  

enter the first matrix element= 

1 2 3

1 2 3  

1 2 3       

enter the second matrix element= 

1 1 1  

2 1 2   

3 2 1    

multiply of the matrix=  

14 9 8      

14 9 8  

14 9 8

Leave a Comment

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