-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmatrix_multiplication.cpp
More file actions
78 lines (65 loc) · 1.58 KB
/
matrix_multiplication.cpp
File metadata and controls
78 lines (65 loc) · 1.58 KB
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
//Write a C++ program to multiply 2 matrices , print not possible if both can't be multiplied
#include<iostream>
#include<vector>
using namespace std;
vector<vector<int> > input()
{
//takes input in a 2d vector and return a 2d vector
int r,c;
cin>>r>>c;
vector<vector<int> > arr(r,vector<int>(c,0));
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
cin>>arr[i][j];
}
return arr;
}
void printMatrix(vector<vector<int> > &arr1)
{
int r1=arr1.size();
int c1=arr1[0].size();
cout<<"The resultant matrix is : \n";
for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
cout<<arr1[i][j]<<" ";
cout<<"\n";
}
}
void multiply(vector<vector<int> > &arr1,vector<vector<int> > &arr2)
{
//Multiplies two matrices and prints the result on screen
//If can't be multiplied then prints , CAN'T BE MULTIPLIED
int r1=arr1.size();
int c1=arr1[0].size();
int r2=arr2.size();
int c2=arr2[0].size();
if(c1==r2)
{
vector<vector<int> > ans(r1,vector<int>(c2,0));//The answer will of order r1xc2
for(int i=0;i<r1;i++)
{
for(int j=0;j<c1;j++)
{
int sum=0;
for(int k=0;k<c1;k++)
{
sum+=(arr1[i][k]*arr2[k][j]);
}
ans[i][j]=sum;
}
}
printMatrix(ans);
}
else
{
cout<<"\nCAN'T BE MULTIPLIED\n";
}
}
int main()
{
vector<vector<int> > arr1=input();
vector<vector<int> > arr2=input();
multiply(arr1,arr2);
}