











Program for Matrix Multiplication Function
Multiply Two Matrices Using Function
On this page we will write C program to multiply two matrices using function.Matrix multiplication is important to understand the basics of C programming.Functions make program more readable and reusable.Hence, we will learn to use function using simple matrix multiplication problem.


C Program to Multiply Two Matrices Using Function
There are two type of matrix:
- Square matrix
- Rectangle matrix
Main Function of the Program
void Matrix_mul (int mat1[][c1], int mat2[][c2]) { int mul[r1][c2]; printf ("Multiplication of given two matrices is:\n"); for (int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { mul[i][j] = 0; for (int k = 0; k < r2; k++) { mul[i][j] += mat1[i][k] * mat2[k][j]; } printf ("%d\t", mul[i][j]); } printf ("\n"); } }
We can create separate function to enter the elements from and user and a separate function for displaying the final multiplied matrix.But here, we are creating one function for multiplication and printing the elements and given two matrices are predefined.
Program: Matrix Multiplication using Functions
#include <stdio.h> #include <stdlib.h> #define r1 2 #define c1 3 #define r2 3 #define c2 2 void Matrix_mul (int mat1[][c1], int mat2[][c2]) { int mul[r1][c2]; printf ("Multiplication of given two matrices is:\n"); for (int i = 0; i < r1; i++) { for (int j = 0; j < c2; j++) { mul[i][j] = 0; for (int k = 0; k < r2; k++) { mul[i][j] += mat1[i][k] * mat2[k][j]; } printf ("%d\t", mul[i][j]); } printf ("\n"); } } int main () { int mat1[r1][c1] = { {0, 1, 2}, {3, 4, 5} }; int mat2[r2][c2] = { {1, 2}, {3, 4}, {5, 6} }; int mul[r1][c2], i, j, k; printf ("matrix 1 is :\n"); for (i = 0; i < r1; i++) { for (j = 0; j < c1; j++) { printf ("%d ", mat1[i][j]); if (j == 3 - 1) { printf ("\n\n"); } } } printf ("matrix 2 is :\n"); for (i = 0; i < r2; i++) { for (j = 0; j < c2; j++) { printf ("%d ", mat2[i][j]); if (j == 2 - 1) { printf ("\n\n"); } } } Matrix_mul (mat1, mat2); return 0; }
Output :
matrix 1 is : 0 1 2 3 4 5 matrix 2 is : 1 2 3 4 5 6 The product of the two matrices is: 13 16 40 52
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment