C program to multiply two matrices

Write a C program to read elements in two matrices and multiply them. Matrix multiplication program in C. How to multiply matrices in C.

Example:
If matrix 1 =
1 2 3
4 5 6
7 8 9

And matrix 2 =
9 8 7
6 5 4
3 2 1

Product of both matrices =
30 24 18
84 69 54
138 114 90

Required knowledge:

Basic C programming, For loop, Array, Matrix

Matrix Multiplication

Multiplication of matrices is different from simple Scalar multiplication of matrix in C. Two matrices can be multiplied only and only if number of columns in the first matrix is same as number of rows in second matrix.
Multiplication of two matrices can be defined as
Matrix multiplication

Program:

/**
 * C program to multiply two matrices
 */

#include <stdio.h>

int main()
{
    int A[3][3], B[3][3], C[3][3];
    int row, col, i, sum;

    /*
     * Reads elements in first matrix from user
     */
    printf("Enter elements in matrix A of size 3x3: \n");
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            scanf("%d", &A[row][col]);
        }
    }

    /*
     * Reads elements in second matrix from user
     */
    printf("\nEnter elements in matrix B of size 3x3: \n");
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            scanf("%d", &B[row][col]);
        }
    }

    /*
     * Multiplies both matrices A*B
     */
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            sum = 0;
            /*
             * Multiplies row of first matrix to column of second matrix
             * And stores the sum of product of elements in sum.
             */
            for(i=0; i<3; i++)
            {
                sum += A[row][i] * B[i][col];
            }

            C[row][col] = sum;
        }
    }

    /*
     * Prints the product of matrices
     */
    printf("\nProduct of Matrix A * B = \n");
    for(row=0; row<3; row++)
    {
        for(col=0; col<3; col++)
        {
            printf("%d ", C[row][col]);
        }
        printf("\n");
    }

    return 0;
} 
Output
X
_
Enter elements in matrix A of size 3x3:
1 2 3
4 5 6
7 8 9

Enter elements in matrix B of size 3x3:
9 8 7
6 5 4
3 2 1

Product of A * B =
30 24 18
84 69 54
138 114 90

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment