+ 1
write a c++ code playground to multiply a*b matrices and store the result in matrix c ?
5 ответов
+ 5
Hello @cyreen
here is your code, I have also posted code on my profile check it out and try your self to determine logic.
#include <iostream>
using namespace std;
int main() {
int a[3][3],b[3][3],c[3][3];
cout<<"Enter data for matrix-a:";
for(int i=0;i<3;i++)
for (int j=0;j<3;j++)
cin>>a[i][j];
cout<<"Enter data for matrix-b:";
for(int i=0;i<3;i++)
for (int j=0;j<3;j++)
cin>>b[i][j];
cout<<endl;
//print matrix-a data
cout<<"Matrix -a:"<<endl;
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
//print matrix-b
cout<<"Matrix -b:"<<endl;
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
cout<<b[i][j]<<" ";
}
cout<<endl;
}
//multiply matrix a and matrix b
for(int i = 0; i < 3; ++i)
{
for(int j = 0; j < 3; ++j)
{
c[i][j] = 0;
for(int k = 0; k < 3; ++k)
{
c[i][j] += a[i][k] * b[k][j];
}
}
}
// print multiplied matrix
cout<<"Matrix-c data are:"<<endl;
for (int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
cout<<c[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
+ 3
yes of course @cyreen
I've minimized the code on my profile you can copy that:
program name: Matrix multiplication
+ 1
Thank you Vishal 😘
but it's too long , i want short solution if you can .
thank you again my love 🙌
+ 1
Ok Vishal 😘
0
To multiply an m×n matrix by an n×p matrix, the n must be the same, and the result is an m×p matrix.
The time complexity of this c program is O(n3).
For Example: If we multiply a 2×4 matrix and a 4×3 matrix, then the product matrix will be a 2×3 matrix.
Here is the code snippet to multiply two matrices.
/* Multiply both matrices */
for(i = 0; i < rows1; i++){
for(j = 0; j < rows2; j++){
for(k = 0; k < cols2; k++){
productMatrix[i][j] += firstMatrix[i][k]*secondMatrix[k][j];
}
}
}
You can check full c/C++ program here
http://www.techcrashcourse.com/2015/03/c-program-for-matrix-multiplication.html
http://www.techcrashcourse.com/2017/01/cpp-program-to-multiply-two-matrices.html