# Matrix Multiplication in C

In this example, You will find a program for matrix multiplication in C and learn how matrix multiply calculates. In the previous article, we do matrix addition in C

The program asks the user for the number of rows and the number of columns then takes elements of two matrices from the user. So we do the calculation on both matrices to find multiply.
The below image shows how the calculation works for 2*2 and 3*3 matrices multiplication in C.
1. The first row elements of first matrix are multiplied with all columns of second matrix.
2. Then second row elements of first matrix are multiplied with all columns of second matrix and so on until the end of the rows of first matrix.
Now, look at the image you understand easily 2*2 or 3*3 matrix multiplication in C programming.

#### Matrix Multiplication in C

``````
#include<stdio.h>
int main()
{
int a,b,c,rows,cols,i,j,k,sum=0;
printf("Enter the Number of Rows");
scanf("%d",&rows);
printf("Enter the Number of Columns");
scanf("%d",&cols);
printf("Enter elements for 1st matrix:\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
scanf("%d",&a[i][j]);
}
printf("Enter elements for 2nd matrix:\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
scanf("%d",&b[i][j]);
}
printf("MATRIX 1:\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
printf("%d  ",a[i][j]);
printf("\n");
}
printf("MATRIX 2:\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
printf("%d  ",b[i][j]);
printf("\n");
}
printf("Multiplication of Two Matrix\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
for(k=0;k<cols;k++)
sum=sum+a[i][k]*b[k][j];
c[i][j]=sum;
sum=0;
}
}
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
printf("%d ",c[i][j]);
printf("\n");
}
return 0;
}
``````

Output

``````
Enter the Number of Rows 2
Enter the Number of Columns 2

MATRIX 1:
1  3
4  2

MATRIX 2:
3  1
3  2

Multiplication of Two Matrix
12 7
18 8

``````
In the Above article, we learn about c matrix multiplication and how it works for 2*2 and 3*3 matrix multiplication. In upcoming tutorials, we discuss subtraction of two matrix, transpose with algorithms in detail. If you learn from the above example then try to solve these which we see in upcoming examples and comment your solution below.

Happy Coding 😊