Matrix Multiplication in C
This program multiplies two matrices and displays the result. Below is the complete C program along with an explanation of its structure and functionality.
Program Structure
- Include Header Files: Standard input-output library is included to handle input and output operations.
- Define Matrix Size: Define the size of the matrices using constants for simplicity.
- Input Matrices: Function to take input for matrices.
- Multiply Matrices: Function to perform the multiplication of two matrices.
- Display Result: Function to display the resultant matrix after multiplication.
- Main Function: The main function to drive the program, calling other functions in sequence.
C Program
#include <stdio.h>
#define ROWS 3
#define COLS 3
// Function to input matrices
void inputMatrix(int matrix[ROWS][COLS], const char* name) {
printf("Enter elements for matrix %s:\n", name);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%s[%d][%d] = ", name, i, j);
scanf("%d", &matrix[i][j]);
}
}
}
// Function to multiply two matrices
void multiplyMatrices(int firstMatrix[ROWS][COLS], int secondMatrix[ROWS][COLS], int resultMatrix[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
resultMatrix[i][j] = 0;
for (int k = 0; k < COLS; k++) {
resultMatrix[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
}
// Function to display a matrix
void displayMatrix(int matrix[ROWS][COLS], const char* name) {
printf("Matrix %s:\n", name);
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int firstMatrix[ROWS][COLS], secondMatrix[ROWS][COLS], resultMatrix[ROWS][COLS];
// Input matrices
inputMatrix(firstMatrix, "A");
inputMatrix(secondMatrix, "B");
// Multiply matrices
multiplyMatrices(firstMatrix, secondMatrix, resultMatrix);
// Display the result
displayMatrix(resultMatrix, "AxB");
return 0;
}
Explanation
The program starts by including the standard I/O library to facilitate input and output operations.
We define the size of the matrices (3×3) using constants for clarity.
The inputMatrix
function takes a matrix and its name as arguments and prompts the user to input values for the matrix elements.
The multiplyMatrices
function performs the multiplication of two matrices. It initializes the result matrix elements to 0 and then computes the product using nested loops.
The displayMatrix
function prints the elements of a given matrix to the console.
The main
function ties everything together by calling these functions in sequence: first, it collects inputs for the two matrices, then it multiplies them, and finally, it displays the result.