Search This Blog

C Program for Matrix Multiplication

This is a c program for Matrix Multiplication. To understand how it works, you should first know how matrix multiplication is done mathematically.

#include <stdio.h>
void main()
{
int m1[10][10],i,j,k,m2[10][10],prod[10][10],r1,c1,r2,c2;
printf("Enter number of rows and columns of first matrix:\n");
scanf("%d%d",&r1,&c1);
printf("Enter number of rows and columns of second matrix:\n");
scanf("%d%d",&r2,&c2);
if(r2==c1)
    {
    printf("Enter elements of First matrix (row wise):\n");
    for(i=0;i<r1;i++)
        for(j=0;j<c1;j++)
            scanf("%d",&m1[i][j]);
    printf("Matrix1 is :\n");
    for(i=0;i<r1;i++)
        {
        for(j=0;j<c1;j++)
            printf("%d ",m1[i][j]);
        printf("\n");
        }
    printf("Enter elements of Second matrix (row wise):\n");
    for(i=0;i<r2;i++)
        for(j=0;j<c2;j++)
            scanf("%d",&m2[i][j]);
    printf("Matrix2 is:\n");
    for(i=0;i<r2;i++)
        {
        for(j=0;j<c2;j++)
            printf("%d ",m2[i][j]);
        printf("\n");
        }
    printf("Product of the Matrices (M1 x M2):\n");
    for(i=0;i<r1;i++)
        {
        for(j=0;j<c2;j++)
            {
            prod[i][j]=0;
            for(k=0;k<r1;k++)
                prod[i][j]+=m1[i][k]*m2[k][j];
            printf("%d\ ",prod[i][j]);
            }
        printf("\n");
        }
    }
else
    {
    printf("Matrices can't be multiplied.\n");
    printf("No. of columns of first matrix and no of rows of second are different.");
    }
}

No comments: