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 and :
is defined only when the no. of columns of is equal to the no. of rows in matrix .
If is an matrix, and is an matrix, then the product matrix would be a matrix,
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:
Ph.D. researcher at Friedrich-Schiller University Jena, Germany. I’m a physicist specializing in computational material science. I write efficient codes for simulating light-matter interactions at atomic scales. I like to develop Physics, DFT, and Machine Learning related apps and software from time to time. Can code in most of the popular languages. I like to share my knowledge in Physics and applications using this Blog and a YouTube channel.