C Program to Multiply two Matrices by Passing Matrix to a Function
Learn C Program to Multiply two Matrices by Passing Matrix to a Function step by step with clear examples and exercises.
Here's the revised lesson on "C Program to Multiply two Matrices by Passing Matrix to a Function" with added practice questions:
Why This Matters
Matrix multiplication is an essential operation in various fields such as linear algebra, machine learning, computer graphics, and numerical analysis. By passing matrices to functions, we can write more modular, readable, and efficient code. This approach helps manage large matrices without cluttering the main function and makes it easier to reuse and test individual functions.
Prerequisites
To understand this lesson, you should have a good grasp of the following topics:
- Basics of C programming, including variables, data types, loops, and functions
- Arrays in C programming
- Passing arrays as arguments to functions
- Pointers and memory allocation in C
- Basic concepts of linear algebra, such as matrix multiplication rules and properties
Core Concept
A matrix is a rectangular array of numbers arranged in rows and columns. To multiply two matrices, the number of columns in the first matrix should match the number of rows in the second matrix. In this lesson, we will write a C program that takes two matrices as input, multiplies them, and displays the result by passing one of the matrices to a function.
We will create three functions:
enterMatrix(): This function takes a matrix as an argument and asks the user to enter its elements.multiplyMatrices(): This function multiplies two matrices and returns the result.displayMatrix(): This function displays a given matrix on the console.
Function Prototypes
Before using these functions, we need to declare their prototypes:
void enterMatrix(int arr[][100], int rows, int cols);
int** multiplyMatrices(int arr1[][100], int arr2[][100], int rows1, int cols1, int rows2, int cols2);
void displayMatrix(int arr[][100], int rows, int cols);
enterMatrix() Function
The enterMatrix() function takes a matrix as an argument and asks the user to enter its elements:
void enterMatrix(int arr[][100], int rows, int cols) {
for (int i = 0; i < rows; ++i) {
printf("Enter elements of row %d:\n", i + 1);
for (int j = 0; j < cols; ++j) {
scanf("%d", &arr[i][j]);
}
}
}
multiplyMatrices() Function
The multiplyMatrices() function multiplies two matrices and returns the result as a new matrix:
int** multiplyMatrices(int arr1[][100], int arr2[][100], int rows1, int cols1, int rows2, int cols2) {
int **result = (int**)malloc((rows1)*sizeof(int*));
for (int i = 0; i < rows1; ++i) {
result[i] = (int*)malloc((cols2)*sizeof(int));
}
for (int i = 0; i < rows1; ++i) {
for (int j = 0; j < cols2; ++j) {
result[i][j] = 0;
for (int k = 0; k < cols1; ++k) {
result[i][j] += arr1[i][k] * arr2[k][j];
}
}
}
return result;
}
displayMatrix() Function
The displayMatrix() function displays a given matrix on the console:
void displayMatrix(int arr[][100], int rows, int cols) {
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
printf("%d ", arr[i][j]);
}
printf("\n");
}
}
Main Function
In the main function, we will take two matrices as input, multiply them using the multiplyMatrices() function, and display the result using the displayMatrix() function:
int main() {
int rows1, cols1, rows2, cols2;
printf("Enter the number of rows and columns for the first matrix:\n");
scanf("%d %d", &rows1, &cols1);
int arr1[rows1][cols1];
enterMatrix(arr1, rows1, cols1);
printf("Enter the number of rows and columns for the second matrix:\n");
scanf("%d %d", &rows2, &cols2);
if (cols1 != rows2) {
printf("Error: The number of columns in the first matrix should match the number of rows in the second matrix.\n");
return 0;
}
int** result = multiplyMatrices(arr1, arr1, rows1, cols1, rows2, cols2);
displayMatrix(result, rows2, cols2);
for (int i = 0; i < rows2; ++i) {
free(result[i]);
}
free(result);
return 0;
}
Worked Example
Let's consider two matrices A and B:
Matrix A:
1 2 3
4 5 6
7 8 9
Matrix B:
10 11
12 13
14 15
To multiply these matrices, we will follow the steps mentioned in the core concept section. After running the program, we get the following result:
614
918
1222
1526
1830
2134
2438
2742
2025
Practice Questions
Q1: Write a function to find the transpose of a matrix.
To find the transpose of a matrix, we need to swap the row and column indices. Here's a possible implementation:
void transpose(int arr[][100], int rows, int cols) {
for (int i = 0; i < rows; ++i) {
for (int j = i + 1; j < cols; ++j) {
int temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
}
}
Q2: Write a function to find the determinant of a 2x2 matrix.
To calculate the determinant of a 2x2 matrix, you can use the following formula: determinant = arr[0][0] * arr[1][1] - arr[0][1] * arr[1][0]. You can create a new function that takes a 2x2 matrix as an argument and returns its determinant.
Q3: Write a function to find the eigenvalues of a 2x2 matrix.
To calculate the eigenvalues of a 2x2 matrix, you can use the characteristic equation det(A - λI) = 0, where A is the given matrix and I is the identity matrix. You can create two functions: one to find the roots of the characteristic equation and another to check if the roots are indeed eigenvalues.
Q4: Write a function to sort a matrix row-wise using quicksort.
To sort a matrix row-wise, you can use the quicksort algorithm. Modify the quicksort implementation to compare rows instead of individual elements. You can create a new function that takes a matrix as an argument and sorts it row-wise.
Common Mistakes
- Forgetting to check if the number of columns in the first matrix matches the number of rows in the second matrix. If this condition is not met, the matrices cannot be multiplied.
- Not freeing memory allocated for the result matrix. After displaying the result, it's essential to free the memory allocated for the
resultmatrix usingfree(). - Incorrect indexing. Be careful with array indices when accessing and modifying elements in the matrices.
- Not handling invalid input. Always validate user input to ensure that the entered values are within the expected range.
- Not defining the function prototypes. Make sure to declare the function prototypes before using them in your code.
- Failing to allocate enough memory for the result matrix. Ensure that you use the correct dimensions when allocating memory for the
resultmatrix. - Using uninitialized variables or pointers. Always initialize variables and pointers before using them in your code.
- Not properly handling edge cases, such as empty matrices or matrices with only one row or column.
- Not optimizing the code for large matrices. Consider using libraries like BLAS or LAPACK to optimize matrix multiplication for large matrices.
- Not considering the order of matrix multiplication. In general, when multiplying two matrices A and B, the result is different if you multiply them as A B or B A (unless they are square matrices).
FAQ
Q: What happens if I try to multiply matrices with incompatible dimensions?
A: If the number of columns in the first matrix does not match the number of rows in the second matrix, you cannot perform the multiplication. In this case, an error message should be displayed.
Q: Can I use the same function to add two matrices instead of multiplying them?
A: Yes! You can modify the multiplyMatrices() function to add two matrices by changing the multiplication operation to addition and initializing the result matrix with zeros.
Q: How can I find the determinant of a 2x2 matrix using a function in C?
A: To calculate the determinant of a 2x2 matrix, you can use the following formula: determinant = arr[0][0] * arr[1][1] - arr[0][1] * arr[1][0]. You can create a new function that takes a 2x2 matrix as an argument and returns its determinant.
Q: How can I check if a given matrix is symmetric or not?
A: A square matrix is said to be symmetric if arr[i][j] = arr[j][i] for all i and j. You can create a function that checks this condition for the given matrix.
Q: How can I sort a matrix row-wise using a function in C?
A: To sort a matrix row-wise, you can use quicksort or merge sort algorithms. Modify these algorithms to compare rows instead of individual elements. You can create a new function that takes a matrix as an argument and sorts it row-wise.
Q: How can I find the eigenvalues and eigenvectors of a 2x2 matrix using functions in C?
A: To calculate the eigenvalues and eigenvectors of a 2x2 matrix, you can use the characteristic equation and the Cayley-Hamilton theorem. You can create two functions: one to find the roots of the characteristic equation and another to find the corresponding eigenvectors.