i was trying to make the program which takes two matrices as an input and display the multiplication of those two matrices but this program wasn,t giving the right answer
‘’’
#include
using namespace std;
int main() {
// your code goes here
int n1,n2,n3;
cin>>n1>>n2>>n3;
int a[n1][n2],b[n2][n3];
for(int i=0;i<n1;i++){
for(int j=0;j<n2;j++){
cin>>a[i][j];
cout<<a[i][j]<<" ";
}
cout<<endl;
}
for(int i=0;i<n2;i++){
for(int j=0;j<n3;j++){
cin>>b[i][j];
cout<<b[i][j]<<" ";
}
cout<<endl;
}
int c[n1][n3]={0};
for(int i=0;i<n1;i++){
for(int j=0;j<n3;j++){
for(int k=0;k<n2;k++){
c[i][j]+=a[i][k]*b[k][j];
}
cout<<c[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
‘’’
I made some changes in your soln now it is showing correct o/p
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n1,n2,n3;
cin>>n1>>n2>>n3;
int a[n1][n2],b[n2][n3],c[n1][n3];
for(int i=0;i<n1;i++){
for(int j=0;j<n2;j++){
cin>>a[i][j];
cout<<a[i][j]<<" ";
}
cout<<endl;
}
for(int i=0;i<n2;i++){
for(int j=0;j<n3;j++){
cin>>b[i][j];
cout<<b[i][j]<<" ";
}
cout<<endl;
}
//int c[n1][n3]={0};
for(int i=0;i<n1;i++){
for(int j=0;j<n3;j++){
c[i][j]=0;
for(int k=0;k<n3;k++){
c[i][j]+=a[i][k]*b[k][j];
}
cout<<c[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
I didn’t get that. if I have already initialized the c array with 0 then why would I have to do it again in the loop
For initializing whole matrix with 0
you can use memset(c,0,sizeof(c))
instead of
c[i][j] = {0}
as latter one can lead to wrong answer in online judge sometimes.
You can read more about the working of the latter syntax from here: c - Initializing entire 2D array with one value - Stack Overflow