Matrix Multiplication using Class (Without friend)

Hi guys. I am working on a matrix multiplication code. Its working but not correctly :).. I would really appreciate if you guys could help me with this..
Thanks.

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include<iostream>
#include<conio.h>
#include<iomanip>

using namespace std;

const int ROW=5;
const int COL=5;

class matrix
{
 int a[ROW][COL];
 int row;
 int col;
 public:
 		matrix () : row(0), col(0)
 		{}
  		void read(int r, int c);
  		void display();
  		matrix multiply (matrix m1, matrix m2);
};

void matrix :: read(int r, int c)
{
 row=r;
 col=c;
 for(int i=1; i<=r; i++)
 for(int j=1; j<=c; j++)
 {
  cout<<"A["<<i<<"]["<<j<<"] : ";
  cin>>a[i][j];
 }
}

void matrix :: display()
{
 	for(int i=1; i<=row; i++)
 	{
 		for (int j=1; j<= col; j++)
  			cout<<setw(4)<<a[i][j];
  		cout<<endl;
 	}
}

matrix matrix :: multiply (matrix m1, matrix m2)
{
 	matrix temp;
 	temp.row=m1.row;
 	temp.col=m2.col;
 	for(int i=1; i<=temp.row; i++)
 	for(int j=1; j<=temp.col; j++)
 	{
  		temp.a[i][j]=0;
  		{            
		  for (int k=0; k<=temp.col; k++)
    			temp.a[i][j] += m1.a[i][k]*m2.a[k][j];
  		}
 	}
 	return temp;
}
int main()
{
 	matrix m1,m2,m3, m4;
 	int r1,c1;
 	cout<<"Enter the order of first matrix : ";
 	cin>>r1>>c1;
 	int r2,c2;
 	cout<<"Enter the order of second matrix : ";
 	cin>>r2>>c2;
 	if(c1!=r2)
     	cout<<"Matrix multiplication not Possible\n";
	else
     {
	 	cout<<"Enter elements of first matrix:\n";
   		m1.read(r1,c1);
   		cout<<"Enter elements of second matrix:\n";
   		m2.read(r2,c2);
   		m4 = m3.multiply (m1,m2);
   		cout<<"Resultant matrix is :\n";
   		m4.display();
     }
  getche();
  return 0;
}
  
I don't have time to look in detail at your code (since I'm at work), but at a glance. Your loops are starting at 1, which would cause an error since arrays start at 0. Also you have them set to <= which could cause to go out of bound. usually should go x < a.size
Thank you so much. It solved my problem.
God Bless you.
Topic archived. No new replies allowed.