Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*tHIS CODE MULTIPLY TWO MATRICES which are dymamiclly allocated AND PRINT THE OUTPUT*/
- /*All matrices are dynamically allocated*/
- /*Let there are 2 matrices mat1 of n1 * m1 & mat2 of n2 * m2. then for matrix to be multiplied m1 should be
- equal to n2 (m1 == n2). After multiplication the product matrix will be of n1 * m2 type.*/
- #include<stdio.h>
- #include<stdlib.h>
- #include<malloc.h>
- void display(int *mat,int row, int column);
- int * multiply_matrix(int *mat1,int row1,int col1,int *mat2,int row2, int col2);
- //taking all these as global variable because each function will use it
- int main()
- { int *mat1, *mat2, *mat3;
- int n1,n2,m1,m2,i;
- srand(time(0));
- printf("Enter value of 'n' & 'm' for the first matrix (n * m): ");
- scanf("%d %d",&n1,&m1);
- printf("Enter value of 'n' & 'm' for the second matrix (n * m): ");
- scanf("%d %d",&n2,&m2);
- /*Dyanamically allocating memeory for both matrices*/
- mat1 = calloc(n1*m1, sizeof(int));
- mat2 = calloc(n2*m2,sizeof(int));
- /*Dynamically allocating memory for product matrix*/
- /*randomly generating first matrix*/
- for(i=0;i<n1*m1;i++)
- mat1[i] = rand()%9 + 1;//generating number between 1 to 9
- /*Randomly generating the second matrix*/
- for(i=0;i<n2*m2;i++)
- mat2[i] = rand()%9 + 1;
- /*multliplying both matrices*/
- mat3 = multiply_matrix(mat1,n1,m1,mat2,n2,m2);
- /*Displaying both the matrices*/
- display(mat1,n1,m1);
- display(mat2,n2,m2);
- /*displaying the product matrix*/
- display(mat3,n1,m2);
- free(mat1);
- free(mat2);
- free(mat3);
- return 0;
- }//main
- void display(int *mat,int row, int column)
- { int i,j;
- for(i=0;i<row;i++)
- {
- for(j=0;j<column;j++)
- printf("%-4d ",mat[i*column + j]);
- printf("\n");
- }
- printf("\n\n");
- }//display
- int* multiply_matrix(int *mat1,int row1,int col1,int *mat2,int row2, int col2)
- { int i,j,k;
- int *prod;
- /*dynamically allocating the product matrix*/
- prod = calloc(row1 * col2, sizeof(int));
- /*Checking multiplication constrants*/
- if(col1 != row2)
- {
- printf("\nThese matrix can not be multiplied: ");
- exit(1);
- }
- for(i=0;i<row1;i++)
- { for(j=0;j<col2;j++)
- {
- for(k=0;k<row2;k++)
- { prod[i * col2 + j] = prod[i * col2 + j] + mat1[i * col1 + k] * mat2[k * col2 + j];/*quite tricky pay attention to it*/
- //printf("%d ",prod[i * col2 + j]);
- }
- }
- }
- return prod;
- }//end of multiply matrix
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement