In this post, we will see how to do matrix multiplication in C.
If we want to multiply two matrices, then number of columns in first matrix must be equal to number of rows in second matrix. If this condition is not satisfied, below program will give you an error message.
Here is simple demonstration of matrix multiplication in C.
Implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include<stdio.h> #include<stdlib.h> #include<stdbool.h> //function of multiplication of two matrix int **mat1,**mat2,**mat; void multiplication(int row1,int col1,int row2,int col2){ //if the col of first matrix is not same with row of second matrix //then return if(col1!=row2){ printf("Column of the first matrix is not same with another matrix"); exit(0); } mat=(int **)malloc(sizeof(int *)*row1); for(int i=0;i<row1 mat malloc for i="0;i<row1;i++){" j="0;j<col2;j++){" int sum="0;" k="0;k<col1;k++){" the th row element of first matrix with column another matrix. void print col printf main row1 number : scanf elements mat1="(int" mat2="(int" new multiplication return></row1></stdbool.h></stdlib.h></stdio.h> |
Output:
Row number of 1st matrix :3
Column number of 1st matrix : 3
Row number of 2nd matrix :3
Column number of 2nd matrix : 3
Enter the elements of 1st matrix
1 2 3
4 5 6
7 8 9
Enter the elements of 2nd matrix
1 2 3
4 5 6
7 8 9
The elements of new matrix
30 36 42
66 81 96
102 126 150
Column number of 1st matrix : 3
Row number of 2nd matrix :3
Column number of 2nd matrix : 3
Enter the elements of 1st matrix
1 2 3
4 5 6
7 8 9
Enter the elements of 2nd matrix
1 2 3
4 5 6
7 8 9
The elements of new matrix
30 36 42
66 81 96
102 126 150
That’s all about matrix multiplication in C.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.