Write a program to perform matrix multiplication. Assume only square matrices of the same dimension.
Input Format:
The input consists of (2*(m*m)+1) integers.
The first integer corresponds to m, the number of rows/columns in the matrix.
The next m*m integers correspond to the elements in the first matrix.
The last m*m elements correspond to the elements in the second matrix. The elements are read in row-wise order, the first row first, then second row and so on. Assume that the maximum value of m is 10.
Sample Input :
Enter the number of rows and columns in 2 matrices
2
Enter the elements in the first matrix
4 5
6 9
Enter the elements in the second matrix
1 2
3 4
Sample Output:
19 28
33 48
Program Code:
#include<stdio.h>
#include<malloc.h>
void find_Sum(int **a,int **b, int m, int n);
int** create1(int m, int n)
{
int **a, i;
a= (int **)malloc(m*sizeof(int *));
for(i=0; i<m; i++)
{
*(a+i) = (int *)malloc(n*sizeof(int ));
}
return a;
}
int** create2(int m, int n)
{
int **b, i;
b= (int **)malloc(m*sizeof(int *));
for(i=0; i<m; i++)
{
*(b+i) = (int *)malloc(n*sizeof(int ));
}
return b;
}
void read1(int **a, int m, int n)
{
int i, j;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", (*(a+i)+j));
}
}
}
void read2(int **b, int m, int n)
{
int i, j;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", (*(b+i)+j));
}
}
}
void find_Sum(int **a,int **b, int m, int n)
{
int i, j,k,sum;
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
sum=0;
for(k=0;k<n;k++)
{
sum=(sum+ (*(*(a+i)+k)) * (*(*(b+k)+j)));
}
printf("%d ",sum);
}
printf("\n");
}
}
int main()
{
int **a, m, n,**b;
printf("Enter the number of rows and columns in 2 matrices\n");
scanf("%d",&m);
n=m;
printf("Enter the elements in the first matrix\n");
a = create1(m,n);
read1(a,m,n);
printf("Enter the elements in the second matrix\n");
b = create2(m,n);
read2(b,m,n);
find_Sum(a,b,m,n);
return 0;
}
Post A Comment:
0 comments: