Program to multiply two matrices in C

#include <stdio.h>
 
 int main()
 {
    const int M=3;      // M=no of rows of A and no of rows of C
    const int N=2;      // N=no of cols of A and no of rows of B
    const int P=2;      // P=no of cols of B and no of cols of C
    int A[M][N],B[N][P],C[M][P];
    int i,j,k;
 
    /*Read in the values for the A matrix*/
    printf("nEnter the elements of matrix A row-wise...n");
    for(i=0;i<M;i++)
        for(j=0;j<N;j++)
            scanf("%d",&A[i][j]);
 
    /*Read in the values for the B matrix*/
    printf("nEnter the elements of matrix B row-wise...n");
    for(j=0;j<N;j++)
        for(k=0;k<P;k++)
            scanf("%d",&B[j][k]);
 
    /*Print the matrix A*/
    printf("nThe matrix A as entered is...n");
    for(i=0;i<M;i++)
    {
        for(j=0;j<N;j++)
            printf("%4d",A[i][j]);
        printf("n");
    }
 
    /*Print the matrix B*/
    printf("nThe matrix B as entered is...n");
    for(j=0;j<N;j++)
    {
        for(k=0;k<P;k++)
            printf("%4d",B[j][k]);
        printf("n");
    }
 
    /*Calculate the product of the two matrices into matrix C*/
    for(i=0;i<M;i++)
        for(j=0;j<N;j++)
        {
            C[i][j]=0;
            for(k=0;k<N;k++)
               C[i][j]=C[i][j]+A[i][k]*B[k][j];
        }
 
    /*Print the result matrix C*/
    printf("nThe matrix C as a product of A and B is...n");
    for(i=0;i<M;i++)
    {
        for(k=0;k<P;k++)
            printf("%4d",C[i][k]);
        printf("n");
    }
    return 0;
 }

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.