#include <stdio.h>
#define ROWS 3
#define COLS 3
void matrixMultiply(int mat1[ROWS][COLS], int mat2[ROWS][COLS], int result[ROWS][COLS]) {
int i, j, k;
// Multiplying matrices
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
result[i][j] = 0;
for (k = 0; k < ROWS; k++) {
result[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
}
void displayMatrix(int mat[ROWS][COLS]) {
int i, j;
// Displaying matrix
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%d\t", mat[i][j]);
}
printf("\n");
}
}
int main() {
int mat1[ROWS][COLS] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
int mat2[ROWS][COLS] = {{9, 8, 7},
{6, 5, 4},
{3, 2, 1}};
int result[ROWS][COLS];
// Multiplying matrices
matrixMultiply(mat1, mat2, result);
// Displaying matrices
printf("Matrix 1:\n");
displayMatrix(mat1);
printf("\nMatrix 2:\n");
displayMatrix(mat2);
printf("\nResultant Matrix:\n");
displayMatrix(result);
return 0;
}
Define Matrix Sizes: The matrices are defined with a constant number of rows and columns. In this example, both matrices are 3x3, but you can adjust the
ROWS
andCOLS
macros to change their sizes.Matrix Multiplication Function (
matrixMultiply
): This function takes three parameters: two matrices (mat1
andmat2
) to be multiplied and a third matrix (result
) where the product will be stored. It uses nested loops to iterate over each element of the result matrix and calculate its value by performing the dot product of the corresponding row inmat1
and column inmat2
Display Matrix Function (displayMatrix
): This function takes a matrix as input and displays its contents row by row, separated by tabs.Main Function (
main
): In themain
function, two matrices (mat1
andmat2
) are initialized with sample values. Then, thematrixMultiply
function is called to compute the product of these matrices, and the result is stored in theresult
matrix. Finally, the contents of all three matrices are displayed using thedisplayMatrix
function.
Comments
Post a Comment