# Thread: Problem in Matrix Multiplication (Using friend function)

1. ## Problem in Matrix Multiplication (Using friend function)

Hi folks,

I'm a beginner in c++. The other day was trying to multiply 2 matrices using friend function. The program did run ,but the result showed some garbage values. plz help..

Code:
```#include<iostream.h>

class matrix
{
int a[10][10],b[10][10],d[10][10],r,c,l,m;
public:
void display (void);
friend void multiply1 (matrix m1);
};

{
int i,j;
cout<<"enter r and c of 1st mat"<<"\n";
cin>>r>>c;
cout<<"enter elements\n";
for(i=0;i<r;i++)
for(j=0;j<c;j++)
cin>>a[i][j];

}
void matrix :: display()
{
int i,j;
cout<<"the elements are --"<<"\n";
cout<<"The elements of 1st\n";
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
cout<<a[i][j]<<" ";
}
cout<<"\n";
}
cout<<r;    //The value being printed here is right.
}
void  multiply1(matrix m1)
{
int i,j,k;
cout<<"\n"<<m1.r; //The value being printed here is always 0 .. :-(
cout<<"\n Enter the dimension (n*m) for the second matrix:";
cin>>m1.l>>m1.m;

cout<<"\n Enter "<< m1.l*m1.m <<" element:";
for(i=0;i<m1.l;i++)
{
for(j=0;j<m1.m;j++)
{
cin>>m1.b[i][j];
}
}

cout<<"The elements of 2nd\n";
for(i=0;i<m1.l;i++)
{
for(j=0;j<m1.m;j++)
{
cout<<m1.b[i][j]<<" ";
}
cout<<"\n";
}

// Multiplication
if(m1.r==m1.m)
{
for(i=0;i<m1.l;i++)
{
for(j=0;j<m1.m;j++)
{
m1.d[i][j]=0;
for(k=0;k<m1.m;k++)
m1.d[i][j]=m1.a[i][k]*m1.b[k][j]+m1.d[i][j];
}
}
cout<<"\n Resultant Matrix:";
for(i=0;i<m1.l;i++)
{
cout<<"\n";
for(j=0;j<m1.m;j++)
cout<<m1.d[i][j]<<"\t";
}
}
}

main()
{
matrix obj,m1,m2;
obj.display();
multiply1(m1);

}```

The rows of the first matrix ('r' here) is not being passed into the method 'multiply'. The value of r when i print is showing 0 always. Any idea???

2. 1. Your multiply function needs to have 'obj' as some kind of parameter, it cannot see your values at the moment.

2. It also needs to be able to store the result in m1 as well. Use a reference parameter to be able to do this.

3. interesting..i had to do the same thing this week as well!
I managed to write a solution..which I will post when I get home...if you want

4. > I managed to write a solution..which I will post when I get home...if you want
You shouldn't just hand over a complete answer just because you can, that would defeat the whole purpose of homework.

wantsree has made a reasonable effort, and will probably get there with a little guidance.