How to perform matrix multiplication in C? Matrix multiplication is a common operation in scientific computing, computer graphics, and various mathematical applications. In this article, we will provide a step-by-step guide on how to perform matrix multiplication in the C programming language.

## Table of Contents

## Matrix Multiplication

Matrix multiplication is a binary operation in which two matrices as the input and another matrix is the output. If matrix A has dimension mxn and matrix B has dimenssion nxp then resultant matrix C will have dimenssion mxp. Each element in the product matrix C is obtained by multiplying elements from corresponding rows of matrix A and columns of B, followed by summing the products.

## C Program for Matrix Multiplication

```
#include <stdio.h>
void main()
{
int m1, m2, n1, n2;
printf("Enter the number of rows in first matrix ");
scanf("%d", &n1);
printf("Enter the number of column in first matrix ");
scanf("%d", &m1);
printf("Enter the number of rows in second matrix ");
scanf("%d", &n2);
printf("Enter the number of column in second matrix ");
scanf("%d", &m2);
if (m1 != n2)
{
printf("Matrix multiplication is not possible ");
}
else
{
int A[n1][m1], B[n2][m2], C[n1][m2];
printf("Enter the element of first Matrix\n");
for (int i = 0; i < n1; i++)
{
for (int j = 0; j < m1; j++)
{
printf("Enter the element at position {%d,%d}", i, j);
scanf("%d", &A[i][j]);
}
}
printf("Enter the element of second Matrix\n");
for (int i = 0; i < n2; i++)
{
for (int j = 0; j < m2; j++)
{
printf("Enter the element at position {%d,%d}", i, j);
scanf("%d", &B[i][j]);
}
}
// loop[ for matrix multiplication
for (int i = 0; i < n1; i++)
{
for (int j = 0; j < m1; j++)
{
C[i][j] = 0;
for (int k = 0; k < m1; k++)
{
C[i][j] += A[i][k] * B[k][j];
}
}
printf("Result after matrix multiplication\n ");
for (int i = 0; i < n1; i++)
{
for (int j = 0; j < m2; j++)
{
printf("%d\t", C[i][j]);
}
printf("\n");
}
}
}
```

### Output

## Explanation of the above C Program

- The above C program starts by asking users to enter the dimensions of both matrices.
- After that program checks if matrixmultiplication is possible or not if (m1 != n2).
- After that program declares three matrices A, B, and C with dimensions specified by the user.
- The program asks the user to enter the elements of both matrices.
- Perform the matrix multiplication by using three for loop and store the result in matrix C.
- At the end, the program prints the result after matrix multiplication.

## 3 thoughts on “Matrix Multiplication in C”