Quantcast
Channel: Java Question Bank » Cpp Programs
Viewing all articles
Browse latest Browse all 22

Matrix Multiplication in C++

$
0
0

**************************************************************

Matrix Multiplication in C++

**************************************************************

This post explains us to calculate matrix multiplication using C++

Source Code :

==========

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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include<conio.h>
#include<stdlib.h>
#include<iostream.h>
class matrix
{
int a[10][10];
public:
void read(int,int);
void write(int,int);
void add(matrix,matrix,int,int);
void sub(matrix,matrix,int,int);
void mul(matrix,matrix,int,int);
} ;
void matrix :: read(int m,int n)
{
int i,j;
cout<<"\n enter the elements in to matrix ::"<<endl;
for(i=0;i<m;i++)
for(j=0;j<n;j++)
cin>>a[i][j];
}
void matrix :: write(int m,int n)
{
cout<<"\n\n Elements in the matrix are :: "<<endl;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cout<<"\t"<<a[i][j];
}
cout<<endl;
}
}
void matrix :: add(matrix m1,matrix m2,int m,int n)
{
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
a[i][j]=m1.a[i][j]+m2.a[i][j];
}
void matrix :: sub(matrix m1,matrix m2,int m,int n)
{
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
a[i][j]=m1.a[i][j]-m2.a[i][j];
}
void matrix :: mul(matrix m1,matrix m2,int n,int p)
{

for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
a[i][j]=0;
for(int k=0;k<p;k++)
{
a[i][j]=a[i][j]+m1.a[i][k]*m2.a[k][j];
}
}

}
void main()
{
int m,n,p,q,ch;
matrix m1,m2,m3,m4,m5;
clrscr();
cout<<"\n Enter order of the matrix A::"<<endl;
cin>>m>>n;
cout<<"\n Enter the order of matrix B::"<<endl;
cin>>p>>q;
m1.read(m,n);
m2.read(p,q);
m1.write(m,n);
m2.write(p,q);
do
{
cout<<"\n\n\t OPERATIONS ON THE MATRICES::"<<endl;
cout<<"\n\n_________________________________________\n"<<endl;
cout<<"1.Addition\n2.substraction\n3.Multiplication\n4.Exit"<<endl;
cout<<"\n\nEnter your choice::";
cin>>ch;
switch(ch)
{
case 1:
if(m==p&&n==q)
{
m3.add(m1,m2,m,n);
m3.write(n,p);
}
else
cout<<"\n Addition is not possible::"<<endl;
break;
case 2:
if(m==p&&n==q)
{
m4.sub(m1,m2,m,n);
m4.write(n,p);
}
else
cout<<"\n Substraction is not possible::"<<endl;
break;
case 3:
if(n==p)
{
m5.mul(m1,m2,n,p);
m5.write(n,p);
}
else
cout<<"multiplication is not possible::"<<endl;
break;
case 4:
exit(0);
default:
cout<<" u have entered wrong choice::"<<endl;
break;
}
}while(1);

}

 

 

53 total views, 7 views today


Viewing all articles
Browse latest Browse all 22

Trending Articles