I am new in programming and was doing a question about multipliaction of two matrix which are inputted from the user.
I think I wrote the correct code for it. However, the output is a null matrix and I cannot pin point the mistake.
#include<iostream>
using namespace std;
int main(){
int row1,col1,row2,col2,val;
cin>>row1>>col1>>col2;
int arr1[row1][col1];
int arr2[row2][col2];
int arr3[row1][col2];
row2=col1;
for(int i=1;i<=row1;i++){
for(int j=1;j<=col1;j++){
cin>>val;
arr1[row1][col1]=val;
}
cout<<endl;
}
for(int i=1;i<=row2;i++){
for(int j=1;j<=col2;j++){
cin>>val;
arr1[row2][col2]=val;
}
cout<<endl;
}
for(int i=1;i<=row1;i++){
for(int k=1;k<=col2;k++){
for(int j=1;j<=col1;j++){
arr3[i][k]+=arr1[i][j]*arr2[j][k];
cout<<arr3[i][k]<<" ";
}
cout<<endl;
}
}
}
>Solution :
When you are setting up your matrices (arr1 and arr2) you are using an incorrect index.
for(int j=1;j<=col1;j++){
arr1[row1][col1]
should be
for(int j=1;j<=col1;j++){
arr1[i][j]
Also, as mentioned, indices in C and C++ go from 0 to N-1, so you are accessing one value out-of-bounds. You should use:
for (int j = 0; j < col1; j++) {
arr1[i][j]
Also, you are setting up arr1 twice, but forgetting to set up arr2.