Matrix Multiplication in C

Matrix Multiplication in C

//Matrix multiplication
#include<stdio.h>
void main()
{
    int m,n,p,q,i,j,k, a[10][10],b[10][10],c[10][10];
    printf("Enter the size of matrix A: \n");
    scanf("%d%d",&m, &n);
    printf("Enter the size of matrix B: \n");
    scanf("%d%d",&p, &q);
    if(n!=p)
    {
    printf("Matrix multiplication is not possible. \n");
    }
    else
    {
        printf("Enter the elements of matrix A: \n");
        for(i=0; i<m; i++)
            for(j=0; j<n; j++)
            {
                scanf("%d",&a[i][j]);
            }
        printf("Enter the elements of matrix B: \n");
        for(i=0; i<p; i++)
            for(j=0; j<q; j++)
            {
                scanf("%d",&b[i][j]);
            }
   
        printf("A-Matrix is \n");
        for(i=0; i<m; i++)
        {
            for(j=0; j<n; j++)
            {
                printf("%d \t", a[i][j]);
            }
            printf("\n");
        }
        printf("B-Matrix is \n");
        for(i=0; i<p; i++)
        {
            for(j=0; j<q; j++)
            {
                printf("%d \t", b[i][j]);
            }
            printf("\n");
        }
        for(i=0; i<m; i++)
            for(j=0; j<q; j++)
            {
                c[i][j]=0;
                for(k=0; k<n; k++)
                c[i][j] = c[i][j] + a[i][k] * b[k][j];
            }
        printf("The resultant matrix C is \n");
        for(i=0; i<m; i++)
        {
            for(j=0; j<q; j++)
            {
                printf("%d \t", c[i][j]);
            }
            printf("\n");
        }
    }
}

OUTPUT


LOGIC

Step 1: We are taking the two Matrix that is Matrix A and B.

Step 2: We are assigning the size of the matrix as row and columns.

Step 3: Then we are taking matrix elements in the matrix A and B where two for loop is used. 

Step 4: Then we are printing the elements as we inserted in the matrix same two for loop is used.

Step 5: Then for loop is used for the multiplication of the two matrix. Multiplication is done by using the code

c[i][j] = c[i][j] + a[i][k] * b[k][j];

Step 6: At last matrix C is displayed after multiplication.

0 Comments