Garbage value in adding of two matrix objects.

I want to add two matrix objects using friend function.The program runs and take inputs but at the end it shows garbage value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<iostream.h>
#include<conio.h>
class matrix
{
	public:
	int a[3][3];
	void getdata()
	{
		for(int i=1;i<=3;i++)
		{
			for(int j=1;j<=3;j++)
			{
				cout<<"Enter numbers for ["<<i<<"]["<<j<<"]";
				cin>>a[i][j];
			}
		}
	}
	void putdata()
	{
		for(int i=1;i<=3;i++)
		{
			for(int j=1;j<=3;j++)
			{
				cout<<a[i][j];
			}
		cout<<endl;
		}
	}
	friend void add(matrix,matrix);
};
void add(matrix m1,matrix m2)
{     //  matrix temp;
	int a,i,j;
	for(i=1;i<=3;i++)
	{      a[3][3]=0;
		for(j=1;j<=3;j++)
		{
		    //	temp.a[i][j]=x.a[i][j]+y.a[i][j];
			cout<<m1.a[i][j]+m2.a[i][j];
		}
		cout<<endl;
	}
    //   return temp;
}
int main()
{
	clrscr();
	matrix m1,m2,m3;
	m1.getdata();
	m2.getdata();
	add(m1,m2);
	m3.putdata();
	getch();
	return 0;
}
Last edited on
Array indices start counting from 0 in C++ so if you have an array of length 3, index 0 will give you the first element and index 2 will give you the last element. Index 3 would be out of bounds.
Last edited on
I know that there for i have written i=1;i<=3 it means it will start from 1 and end on 3.
but main question is that it gives garbage value in addition.
m3.putdata(); will print garbage because the array elements of m3 has not been initialized. Instead of printing from the add function you might want to return a matrix object that you can assign to m3.

1
2
m3 = add(m1, m2);
m3.putdata();
Last edited on
i have tried but no luck
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<iostream.h>
#include<string.h>
#include<conio.h>
class matrix
{
	public:
	int a[3][3];
	void getdata()
	{
		for(int i=1;i<=3;i++)
		{
			for(int j=1;j<=3;j++)
			{
				cout<<"Enter numbers for ["<<i<<"]["<<j<<"]";
				cin>>a[i][j];
			}
		}
	}
	void putdata()
	{
		for(int i=1;i<=3;i++)
		{
			for(int j=1;j<=3;j++)
			{
				cout<<a[i][j];
			}
		cout<<"\n";
		}
	}
	friend matrix add(matrix,matrix);
};
matrix add(matrix x,matrix y)
{       matrix temp;
	int i,j;
	for(i=1;i<=3;i++)
	{
		for(j=1;j<=3;j++)
		{
		    temp.a[i][j]=x.a[i][j]+y.a[i][j];
//		    cout<<temp.a[i][j];
		}
		cout<<"\n";
	}
       return temp;
}
int main()
{
	clrscr();
	matrix m1,m2,m3;
	m1.getdata();
	m2.getdata();
	m3=add(m1,m2);
	m3.putdata();
	getch();
	return 0;
}
Topic archived. No new replies allowed.