forked from Samiullah-Kalhoro/hacktoberfest_21
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathMatrixMultiplication.c
88 lines (75 loc) · 1.81 KB
/
MatrixMultiplication.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include<stdio.h>
#include<stdlib.h>
void product(int **A, int **B, int R1, int C1, int R2, int C2)
{
int **C = (int **) malloc(sizeof(int *) * R1);
for(int i=0; i<R1; i++)
C[i] = (int *)malloc(sizeof(int) * C2);
int sum=0;
for (int i = 0; i < R1; i++)
{
for (int j = 0; j < C2; j++) {
for (int k = 0; k < C1; k++)
{
sum = sum + A[i][k]*B[k][i];
}
C[i][j] = sum;
sum = 0;
}
}
printf("\n\nProduct:\n");
for(int i=0; i<R1; ++i)
{
for(int j=0; j<C2; ++j)
printf("%d\t", C[i][j]);
printf("\n");
}
}
int main()
{
int R1, C1, R2, C2;
printf("Enter number of rows of matrix 1:");
scanf("%d", &R1);
printf("Enter number of columns of matrix 1:");
scanf("%d", &C1);
printf("\n\nEnter number of rows of matrix 2:");
scanf("%d", &R2);
printf("Enter number of columns of matrix 2:");
scanf("%d", &C2);
if(C1!=R2)
{
printf("Multiplication not possible.");
return 1;
}
int **A = (int **) malloc(sizeof(int *) * R1);
int **B = (int **) malloc(sizeof(int *) * R2);
/* Allocating memory for the col of three matrices. */
for(int i=0; i<R1; i++)
A[i] = (int *)malloc(sizeof(int) * C1);
for(int i=0; i<R2; i++)
B[i] = (int *)malloc(sizeof(int) * C2);
printf("Enter the elements of matrix 1:\n");
for(int i=0; i<R1; ++i)
for(int j=0; j<C1; ++j)
scanf("%d", &A[i][j]);
printf("\n\nEnter the elements of matrix 2:\n");
for(int i=0; i<R2; ++i)
for(int j=0; j<C2; ++j)
scanf("%d", &B[i][j]);
printf("\n\nMatrix 1:\n");
for(int i=0; i<R1; ++i)
{
for(int j=0; j<C1; ++j)
printf("%d\t", A[i][j]);
printf("\n");
}
printf("\n\nMatrix 2:\n");
for(int i=0; i<R2; ++i)
{
for(int j=0; j<C2; ++j)
printf("%d\t", B[i][j]);
printf("\n");
}
product(A, B, R1, C1, R2, C2);
return 0;
}