Question

Write a program to find the product of two matrices. For example, product of Matrix A of order 2x3 and Matrix B of order 3x2 can be calculated as:

matrix-multiplication

Note:

The number of columns of the 1st matrix must equal the number of rows of the 2nd matrix.

And the result will have the same number of rows as the 1st matrix, and the same number of columns as the 2nd matrix.

Source Code

#include <stdio.h>

void input(int matrix[][10], int, int);
void display(int matrix[][10], int, int);
void product(int matrix1[][10], int matrix2[][10], int matrix3[][10], int, int, int, int);

int main()
{
    int r1, c1, r2, c2;

    int A[10][10], B[10][10], C[10][10];

    printf("Enter number of rows of matrix 1:");
    scanf("%d", &r1);

    printf("Enter number of columns of matrix 1:");
    scanf("%d", &c1);

    printf("Enter number of rows of matrix 2:");
    scanf("%d", &r2);

    printf("Enter number of columns of matrix 2:");
    scanf("%d", &c2);

    if (c1 == r2)
    {
        printf("\nArray 1 :\n");
        input(A, r1, c1);
        printf("\n");
        display(A, r1, c1);
        printf("\n");

        printf("Array 2 :\n");
        input(B, r2, c2);
        printf("\n");
        display(B, r2, c2);
        printf("\n");

        product(A, B, C, r1, c1, r2, c2);
        printf("Array 3 :\n");
        display(C, r1, c2);
    }
    else
    {
        printf("Matrix multiplication is not possible");
    }
    return 0;
}

void input(int matrix[][10], int m, int n)
{
    int i, j;
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            printf("Enter data in [%d][%d] : ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }
}

void display(int matrix[][10], int m, int n)
{
    int i, j;
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }
}

/* product of matrix1 size m1xn1 and matrix2 size m2xn2 */
void product(int matrix1[][10], int matrix2[][10], int matrix3[][10], int m1, int n1, int m2, int n2)
{
    int i, j, t;
    for (i = 0; i < m1; i++)
    {
        for (j = 0; j < n2; j++)
        {
            matrix3[i][j] = 0;
            for (t = 0; t < n1; t++)
            {
                matrix3[i][j] += matrix1[i][t] * matrix2[t][j];
            }
        }
    }
}

Output

Enter number of rows of matrix 1:2
Enter number of columns of matrix 1:3
Enter number of rows of matrix 2:3
Enter number of columns of matrix 2:2

Array 1 :
Enter data in [0][0] : 10
Enter data in [0][1] : 20
Enter data in [0][2] : 30
Enter data in [1][0] : 40
Enter data in [1][1] : 50
Enter data in [1][2] : 60

10      20      30
40      50      60

Array 2 :
Enter data in [0][0] : 2
Enter data in [0][1] : 3
Enter data in [1][0] : 4
Enter data in [1][1] : 5
Enter data in [2][0] : 6
Enter data in [2][1] : 7

2        3
4        5
6        7

Array 3 :
280      340
640      790