Functions are a very important topic in all of Programming. Functions let you organize your code better and also help in not repeating yourself honoring the DRY (Don't Repeat Yourself) principle.
This video introduces you to how functions work in C Programming.
We have discussed about Matrix arithmetic in my recent youtube tutorial.
In that, I have already shown how Matrix addition and subtraction can be done and asked you to try multiplication themselves. Hopefully you have been able to do that Or atleast tried it out before coming here to see my solution.
For this example, I have taken two matrices as follows.
Matrix1 has 3 rows and 4 columns and Matrix2 has 4 rows and 3 columns. And now, the code to multiply these two matrices.
#include "stdio.h"
main() {
int matrix1[3][4] = { {1,2,3,4}, {3,4,1,2}, {4,1,2,3} };
int matrix2[4][3] = { {0,1,2}, {1,2,0}, {2,0,1}, {1,0,2} };
// Values from the matrices. No. of columns in matrix1 = No. of rows in matrix2. Matrix Multiplication possible
int rows1 = 3, cols1 = 4, rows2 = 4, cols2 = 3;
// Initialize the resultant matrix with all zeroes
int mult_matrix[3][3] = {0};
// Loop variables
int i=0, j=0, k=0;
for(i = 0; i < rows1; i++) {
for(j = 0; j < cols2; j++) {
for(k = 0; k < cols1; k++) {
// Since we are initializing with zero, we can add new values to the previous value to get the final value
mult_matrix[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Print the new matrix
for(i = 0; i < rows1; i++) {
for(j = 0; j < cols2; j++) {
printf("%d ", mult_matrix[i][j]);
}
printf("\n");
}
}
And when you run this program, you get the following output as one would expect:
12 5 13
8 11 11
8 6 16
Press any key to continue . . .
The comments, along with the explanation in the video should be enough for you to understand this code directly.But, do reach out on social media for any queries.
That's all for this article.
As, always, Have a happy reading and Stay Awesome !
If you have liked this article and would like to see more, subscribe to our Facebook and G+ pages.