## Matrix multiplication in C

Here we will see some program of matrix multiplication in C. At first we will take input from the user of two matrix element and then we will perform our matrix multiplication through a C program. Then we will print the output of multiplied matrix.

To make a matrix multiplication program we have to know the method of multiply two matrix. Se the multiplication method bellow to know more about matrix multiplication.

We can multiply two matrix if and only if the column number of first matrix is equal to the row number of second matrix.

Multiplication method of 2 * 2 matrix. Multiplication method of 3 * 3 matrix is also given here. ## C program for matrix multiplication

In this program we will take user inputs the order and element of the two matrix and then print error message if the multiplication is not possible. And print the output of multiplied matrix if multiplication is possible.

``````// C program for matrix multiplication
#include <stdio.h>
int main(){
int row1, col1, row2, col2, i, j, k, sum = 0;
int firstMatrix, secondMatrix, mulMatrix;

printf("Enter number of rows and columns for first matrix here : ");
scanf("%d%d", &row1, &col1);
printf("Enter all the elements of first matrix : \n");

for (i = 0; i < row1; i++){      // scanning element of first matrix
for (j = 0; j < col1; j++){
scanf("%d", &firstMatrix[i][j]);
}
}
printf("Enter number of rows and columns for second matrix here : ");
scanf("%d%d", &row2, &col2);

if (col1 != row2){
printf("Multiplication is not possible.\n");
}else{
printf("Enter all the elements of second matrix : \n");

for (i = 0; i < row2; i++){      // scanning elements of second matrix
for (j = 0; j < col2; j++){
scanf("%d", &secondMatrix[i][j]);
}
}

for (i = 0; i < row1; i++) {       // multiplying them
for (j = 0; j < col1; j++) {
for (k = 0; k < row2; k++) {
sum = sum + firstMatrix[i][k]*secondMatrix[k][j];
}
mulMatrix[i][j] = sum;
sum = 0;
}
}

printf("Product of this two matrix is : \n");

for (i = 0; i < row1; i++) {         // printing result
for (j = 0; j < col2; j++)
printf("%d\t", mulMatrix[i][j]);

printf("\n");
}
}
return 0;
}
``````

### Output of this matrix multiplication program

``````Enter number of rows and columns for first matrix here : 3 3
Enter all the elements of first matrix :
1 2 3
4 5 6
7 8 9
Enter number of rows and columns for second matrix here : 3 3
Enter all the elements of second matrix :
9 8 7
6 5 4
3 2 1
Product of this two matrix is :
30      24      18
84      69      54
138     114     90``````
``````Enter number of rows and columns for first matrix here : 2 2
Enter all the elements of first matrix :
1 2
3 4
Enter number of rows and columns for second matrix here : 3 2
Multiplication is not possible.``````

Previous pageAssembly code in C

Next pageHCF and LCM in C