Home

A program to find the product of two matrices and print the resultant matrix

C Programming Language 064

The following code shows how to write a program to find the product of two matrices and print the resultant matrix.

Program

#include <stdio.h>

void main()
{
    int a[10][10], b[10][10], c[10][10], m, n, p, q, i, j, k;
    printf("Enter order of 1st matrix - m,n [m x n]: ");
    scanf("%d %d", &m, &n);

    printf("Enter order of 2nd matrix - p,q [p x q]: ");
    scanf("%d %d", &p, &q);

    if (n != p)
    {
        printf("Multiplication not possible");
    }
    else
    {
        printf("Enter values of 1st matrix [%d x %d]\n", m, n);
        for (i = 0; i < m; i++)
        {
            for (j = 0; j < n; j++)
            {
                scanf("%d", &a[i][j]);
            }
        }

        printf("Enter values of 2nd matrix [%d x %d]\n", p, q);
        for (i = 0; i < p; i++)
        {
            for (j = 0; j < q; j++)
            {
                scanf("%d", &b[i][j]);
            }
        }

        printf("After multiplication:\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("%d\t", c[i][j]);
            }
            printf("\n");
        }
    }

    printf("\n");
}

Result

Enter order of 1st matrix - m,n [m x n]: 2 3
Enter order of 2nd matrix - p,q [p x q]: 3 2
Enter values of 1st matrix [2 x 3]
1 2 3
4 5 6
Enter values of 2nd matrix [3 x 2]
10 11
20 21
30 31
After multiplication:
140     146
320     335
Enter order of 1st matrix - m,n [m x n]: 2 3
Enter order of 2nd matrix - p,q [p x q]: 4 1
Multiplication not possible


Last Updated on

Next Post: Rules vs Guidelines →

Comments