Sure! Matrix multiplication in C can be implemented using nested loops. Here’s an example of how you can multiply two matrices in C:
#include <stdio.h> #define ROWS1 3 #define COLS1 3 #define ROWS2 COLS1 #define COLS2 2 void matrix_multiply(int mat1[][COLS1], int mat2[][COLS2], int result[][COLS2]) { int i, j, k; // Perform matrix multiplication for (i = 0; i < ROWS1; i++) { for (j = 0; j < COLS2; j++) { result[i][j] = 0; for (k = 0; k < ROWS2; k++) { result[i][j] += mat1[i][k] * mat2[k][j]; } } } } void display_matrix(int mat[][COLS2], int rows, int cols) { int i, j; for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) { printf("%d ", mat[i][j]); } printf("\n"); } } int main() { int matrix1[ROWS1][COLS1] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int matrix2[ROWS2][COLS2] = { {1, 2}, {3, 4}, {5, 6} }; int result[ROWS1][COLS2]; matrix_multiply(matrix1, matrix2, result); printf("Matrix 1:\n"); display_matrix(matrix1, ROWS1, COLS1); printf("\nMatrix 2:\n"); display_matrix(matrix2, ROWS2, COLS2); printf("\nResult:\n"); display_matrix(result, ROWS1, COLS2); return 0; }
In this example, matrix_multiply()
is a function that performs matrix multiplication. It takes in two matrices (mat1
and mat2
) and stores the result in the result
matrix. The display_matrix()
function is used to print the matrices.
In the main()
function, we define two matrices (matrix1
and matrix2
) and the result
matrix. We then call the matrix_multiply()
function to perform the multiplication and store the result. Finally, we display the original matrices and the resulting matrix.
Note that the dimensions of the matrices are defined using the #define
preprocessor directives at the beginning of the code. You can modify these values to match the dimensions of your matrices.