C Program For Matrix Multiplication Using Functions
This article will guide you through creating a C program to perform matrix multiplication, specifically focusing on how to structure your code using functions for better organization and reusability. You will learn to implement separate functions for inputting matrix elements, performing the multiplication, and displaying the resulting matrix.
Problem Statement
Matrix multiplication is a fundamental operation in linear algebra, widely used in various computational fields. Implementing it directly within the main function can lead to verbose and less readable code, especially when dealing with multiple matrices or when the logic needs to be reused. The challenge is to structure the program in a modular way that enhances clarity, maintainability, and reusability, particularly for operations like input, processing, and output of matrices.
Example
Consider two 2x2 matrices, A and B:
Matrix A:
1 2
3 4
Matrix B:
5 6
7 8
Their product, C = A * B, would be:
(1*5 + 2*7) (1*6 + 2*8) = (5 + 14) (6 + 16) = 19 22
(3*5 + 4*7) (3*6 + 4*8) = (15 + 28) (18 + 32) = 43 50
Resulting Matrix C:
19 22
43 50
Background & Knowledge Prerequisites
To effectively understand this article, you should have a basic understanding of:
- C Language Fundamentals: Variables, data types, basic input/output.
- Arrays: Declaring and manipulating one-dimensional and two-dimensional arrays.
- Loops:
forloops for iteration. - Functions: Declaring, defining, and calling functions, including passing arrays to functions.
No specific imports beyond standard I/O (stdio.h) are required for this program.
Use Cases or Case Studies
Matrix multiplication is a cornerstone operation across many domains:
- Computer Graphics: Used extensively for transformations like scaling, rotation, and translation of objects in 2D and 3D space.
- Machine Learning and Deep Learning: Core to neural networks, especially in layers like fully connected layers, where weights are multiplied by input features.
- Image Processing: Applied in filters for blurring, sharpening, edge detection, and other image transformations.
- Physics and Engineering: Solving systems of linear equations, simulating physical systems, and performing structural analysis.
- Cryptography: Used in various encryption algorithms, particularly those based on linear transformations.
Solution Approaches
For multiplying matrices using functions, a common and effective approach involves breaking down the problem into three logical parts: input, multiplication, and display. Each part is handled by a dedicated function.
Approach: Modular Matrix Multiplication with Functions
This approach uses three distinct functions to manage the matrix operations: one to get input from the user, one to perform the multiplication logic, and one to print the resulting matrix. This significantly improves code structure and readability.
One-line summary: Decomposes matrix multiplication into functions for input, computation, and output, improving modularity.
// Matrix Multiplication Using Functions
#include <stdio.h>
// Function to get matrix elements from the user
void getMatrixElements(int matrix[][10], int rows, int cols, char name) {
printf("Enter elements for Matrix %c (%dx%d):\\n", name, rows, cols);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
printf("Enter element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
}
// Function to multiply two matrices
void multiplyMatrices(int firstMatrix[][10], int secondMatrix[][10], int resultMatrix[][10], int r1, int c1, int r2, int c2) {
// Initializing elements of result matrix to 0
for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c2; ++j) {
resultMatrix[i][j] = 0;
}
}
// Multiplying firstMatrix and secondMatrix and storing it in resultMatrix
for (int i = 0; i < r1; ++i) {
for (int j = 0; j < c2; ++j) {
for (int k = 0; k < c1; ++k) {
resultMatrix[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
}
// Function to display a matrix
void displayMatrix(int matrix[][10], int rows, int cols, char name) {
printf("\\nMatrix %c:\\n", name);
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
printf("%d\\t", matrix[i][j]);
}
printf("\\n");
}
}
int main() {
int firstMatrix[10][10], secondMatrix[10][10], resultMatrix[10][10];
int r1, c1, r2, c2;
// Step 1: Get dimensions for the first matrix
printf("Enter rows and columns for first matrix: ");
scanf("%d %d", &r1, &c1);
// Step 2: Get dimensions for the second matrix
printf("Enter rows and columns for second matrix: ");
scanf("%d %d", &r2, &c2);
// Step 3: Validate matrix dimensions for multiplication
while (c1 != r2) {
printf("Error! Column of first matrix not equal to row of second.\\n");
printf("Enter rows and columns for first matrix again: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and columns for second matrix again: ");
scanf("%d %d", &r2, &c2);
}
// Step 4: Get elements for the first matrix using a function
getMatrixElements(firstMatrix, r1, c1, 'A');
// Step 5: Get elements for the second matrix using a function
getMatrixElements(secondMatrix, r2, c2, 'B');
// Step 6: Perform matrix multiplication using a function
multiplyMatrices(firstMatrix, secondMatrix, resultMatrix, r1, c1, r2, c2);
// Step 7: Display the matrices and the result using a function
displayMatrix(firstMatrix, r1, c1, 'A');
displayMatrix(secondMatrix, r2, c2, 'B');
displayMatrix(resultMatrix, r1, c2, 'C'); // Result matrix dimensions are r1 x c2
return 0;
}
Sample Output:
Enter rows and columns for first matrix: 2 3
Enter rows and columns for second matrix: 3 2
Enter elements for Matrix A (2x3):
Enter element [0][0]: 1
Enter element [0][1]: 2
Enter element [0][2]: 3
Enter element [1][0]: 4
Enter element [1][1]: 5
Enter element [1][2]: 6
Enter elements for Matrix B (3x2):
Enter element [0][0]: 7
Enter element [0][1]: 8
Enter element [1][0]: 9
Enter element [1][1]: 10
Enter element [2][0]: 11
Enter element [2][1]: 12
Matrix A:
1 2 3
4 5 6
Matrix B:
7 8
9 10
11 12
Matrix C:
58 64
139 154
Stepwise Explanation:
getMatrixElements(int matrix[][10], int rows, int cols, char name):- This function takes an integer 2D array, its dimensions (
rows,cols), and a charactername(e.g., 'A', 'B') to identify the matrix for user prompts.
- This function takes an integer 2D array, its dimensions (
for loops to iterate through each cell of the matrix.scanf is used to read integer values from the user for each element, storing them directly into the passed matrix.multiplyMatrices(int firstMatrix[][10], int secondMatrix[][10], int resultMatrix[][10], int r1, int c1, int r2, int c2):- This function takes two source matrices (
firstMatrix,secondMatrix), a destination matrix (resultMatrix), and their respective dimensions (r1,c1for first,r2,c2for second).
- This function takes two source matrices (
resultMatrix to 0. This is crucial because matrix multiplication involves summing products.for loops:i and j) iterate through the rows of the firstMatrix and columns of the secondMatrix, determining the position in the resultMatrix.k) iterates through the columns of the firstMatrix (which must be equal to the rows of the secondMatrix for valid multiplication).resultMatrix[i][j] += firstMatrix[i][k] * secondMatrix[k][j]; performs the dot product for each element of the result matrix.displayMatrix(int matrix[][10], int rows, int cols, char name):- This function takes a 2D integer array, its dimensions, and a name character.
for loops to iterate through and print each element of the matrix, followed by a tab (\t) for formatting.\n) is printed to ensure correct matrix display.main()function:- Declares three 2D arrays (
firstMatrix,secondMatrix,resultMatrix) to store the matrices. Their sizes are fixed at10x10as a common practice for demonstration, assuming matrices won't exceed this.
- Declares three 2D arrays (
while loop to validate the dimensions: c1 (columns of first matrix) must equal r2 (rows of second matrix) for multiplication to be possible. If not, it re-prompts for dimensions.getMatrixElements twice to populate firstMatrix and secondMatrix.multiplyMatrices to perform the actual multiplication and store the result in resultMatrix.displayMatrix three times: once for each input matrix and once for the resulting product matrix.Conclusion
Using functions for matrix operations significantly improves the modularity and readability of C programs. By encapsulating distinct tasks like input, multiplication, and output into separate functions, the main function remains clean and easy to understand, primarily focusing on orchestrating the calls to these specialized functions. This approach also makes the code more maintainable and allows for easier reuse of individual functionalities in different parts of a larger application.
Summary
- Matrix multiplication involves multiplying corresponding elements of rows and columns and summing them.
- Dimensions must be compatible: columns of the first matrix must equal rows of the second.
- Functions (
getMatrixElements,multiplyMatrices,displayMatrix) enhance code structure. -
getMatrixElementshandles user input for matrix elements. -
multiplyMatricescontains the core triple-nested loop logic for calculating the product. -
displayMatrixprints the matrix in a readable format. - Modular programming with functions leads to cleaner, more maintainable, and reusable code.