-
Notifications
You must be signed in to change notification settings - Fork 0
/
matrix_addition_multiplication.c
73 lines (65 loc) · 1.85 KB
/
matrix_addition_multiplication.c
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
#include <stdio.h>
#define SIZE 50
struct mat {
int row;
int col;
int value[SIZE][SIZE];
};
void scan_mat(struct mat *);
void print_mat(const struct mat *);
void add_mat(const struct mat *, const struct mat *, struct mat *);
void mul_mat(const struct mat *, const struct mat *, struct mat *);
int main(void) {
struct mat m1, m2, result;
char op;
scan_mat(&m1);
scanf(" %c", &op);
scan_mat(&m2);
switch (op) {
case '+':
add_mat(&m1, &m2, &result);
break;
case '*':
mul_mat(&m1, &m2, &result);
break;
}
print_mat(&result);
return 0;
}
void scan_mat(struct mat *m_p) {
scanf("%d %d", &(*m_p).row, &m_p->col);
for (int i = 0; i < m_p->row; ++i)
for (int j = 0; j < m_p->col; ++j)
scanf("%d", &m_p->value[i][j]);
}
void print_mat(const struct mat *m_p){
for (int i = 0; i < m_p->row; ++i) {
for (int j = 0; j < m_p->col; ++j) {
printf("%d ", m_p->value[i][j]);
if (j == m_p->col - 1)
printf("\n");
}
}
}
void add_mat(const struct mat *m1_p, const struct mat *m2_p, struct mat *result_p) { // matrix addition
result_p->col=m1_p->col;
result_p->row=m1_p->row;
for(int i=0;i<result_p->row;++i){
for(int j=0;j<result_p->col;++j){
result_p->value[i][j]=m1_p->value[i][j]+m2_p->value[i][j];
}
}
}
void mul_mat(const struct mat *m1_p, const struct mat *m2_p, struct mat *result_p) { // matrix multiplication
result_p->row=m1_p->row;
result_p->col=m2_p->col;
int value;
for(int i=0;i<result_p->row;++i){
for(int j=0;j<result_p->col;++j){
result_p->value[i][j]=0;
for(int k=0;k<m1_p->col;++k){
result_p->value[i][j]+=m1_p->value[i][k]*m2_p->value[k][j];
}
}
}
}