C Program to Multiply two Matrices with Input

#include <stdio.h>
#include <conio.h>
void main()
{
    int a[10][10],b[10][10],p[10][10];
    int i,j,k;
    int r1,c1,r2,c2;
    AGAIN: printf("For 1st matrix, Enter row and column:: ");
    scanf("%d%d",&r1,&c1);
    printf("\nFor 2nd matrix, Enter row and column:: ");
    scanf("%d%d",&r2,&c2);

    /*if column of 1st matrix is not equal to row of 1st matrix, enter again*/
    if(c1!=r2)
    {
        printf("Matrix order mismatch\n");
        goto AGAIN;
    }

    /*entering elements of 1st matrix*/
    printf("For 1st matrix(%d*%d)\n",r1,c1);
    for(i=0;i<r1;i++)
        for(j=0;j<c1;j++)
            scanf("%d",&a[i][j]);
    
    /*entering elements of 2nd matrix*/
    printf("For 2nd matrix(%d*%d)\n",r2,c2);
    for(i=0;i<r2;i++)
        for(j=0;j<c2;j++)
            scanf("%d",&b[i][j]);

    /*initializing product matrix p to zero(0)*/
    for(i=0;i<r1;i++)
        for(j=0;j<c2;j++)
            p[i][j]=0;

    /*multiplying the matrices*/
    printf("Matrix multiplication is: \n");
    for(i=0;i<r1;i++)
        for(j=0;j<c2;j++)
            for(k=0;k<r2;k++)
                p[i][j]+=a[i][k]*b[k][j];

    /*displaying the product matrix*/
    for(i=0;i<r1;i++)
    {
        for(j=0;j<c2;j++)
            printf("%d ",p[i][j]);
        printf("\n");
    }
    getch();
}

OUTPUT:

No comments:

Post a Comment