Program to Multiply two Matrices by Passing Matrix to a Function - (C Programs)
In C programming, it is common to work with matrices of data. Multiplying two matrices is a common operation that can be done efficiently using C. In this tutorial, we'll discuss a program that multiplies two matrices by passing them to a function.
Syntax
void matrix_multiply(int m, int n, int p, int q, int mat1[][MAX], int mat2[][MAX], int res[][MAX]);
m
- number of rows in the first matrixn
- number of columns in the first matrixp
- number of rows in the second matrixq
- number of columns in the second matrixmat1
- the first matrixmat2
- the second matrixres
- the resulting matrix
Example
#include <stdio.h>
#define MAX 10
void matrix_multiply(int m, int n, int p, int q, int mat1[][MAX], int mat2[][MAX], int res[][MAX]);
int main()
{
int m, n, p, q, i, j;
int mat1[MAX][MAX], mat2[MAX][MAX], res[MAX][MAX];
printf("Enter the number of rows and columns of first matrix: ");
scanf("%d %d", &m, &n);
printf("Enter the elements of first matrix: ");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", &mat1[i][j]);
}
}
printf("Enter the number of rows and columns of second matrix: ");
scanf("%d %d", &p, &q);
if(n != p)
{
printf("Matrices cannot be multiplied!");
return 0;
}
printf("Enter the elements of second matrix: ");
for(i=0; i<p; i++)
{
for(j=0; j<q; j++)
{
scanf("%d", &mat2[i][j]);
}
}
matrix_multiply(m, n, p, q, mat1, mat2, res);
printf("Product of the matrices:\n");
for(i=0; i<m; i++)
{
for(j=0; j<q; j++)
{
printf("%d\t", res[i][j]);
}
printf("\n");
}
return 0;
}
void matrix_multiply(int m, int n, int p, int q, int mat1[][MAX], int mat2[][MAX], int res[][MAX])
{
int i, j, k;
for(i=0; i<m; i++)
{
for(j=0; j<q; j++)
{
res[i][j] = 0;
for(k=0; k<n; k++)
{
res[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}
Output
Enter the number of rows and columns of first matrix: 2 3
Enter the elements of first matrix: 1 2 3 4 5 6
Enter the number of rows and columns of second matrix: 3 2
Enter the elements of second matrix: 7 8 9 10 11 12
Product of the matrices:
58 64
139 154
Explanation
This program multiplies two matrices by passing them to a function. The program prompts the user to enter the dimensions of the matrices and their elements. It then calls the matrix_multiply()
function to perform the multiplication and stores the result in a new matrix. Finally, it prints the resulting matrix to the console.
Use
This program is useful whenever you need to multiply two matrices in C programming. It can be used in a variety of applications, from scientific computing to data analysis.
Summary
In this tutorial, we discussed a program that multiplies two matrices by passing them to a function in C programming. We covered the syntax, example, output, explanation, use, and importance of this program. By using this program, you can easily multiply two matrices in C and use the result for further computations.