C - Program - Matrix Multiplication
To perform matrix multiplication in C, you can use nested loops to iterate over the elements of the matrices and perform the necessary calculations. Here's an example program that demonstrates matrix multiplication:
#include <stdio.h>
#define ROWS_A 3
#define COLS_A 2
#define ROWS_B COLS_A
#define COLS_B 3
void multiplyMatrices(int matrixA[ROWS_A][COLS_A], int matrixB[ROWS_B][COLS_B], int result[ROWS_A][COLS_B]) {
for (int i = 0; i < ROWS_A; i++) {
for (int j = 0; j < COLS_B; j++) {
result[i][j] = 0;
for (int k = 0; k < COLS_A; k++) {
result[i][j] += matrixA[i][k] * matrixB[k][j];
}
}
}
}
void printMatrix(int matrix[ROWS_A][COLS_B], int rows, int cols) {
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 matrixA[ROWS_A][COLS_A] = {{1, 2},
{3, 4},
{5, 6}};
int matrixB[ROWS_B][COLS_B] = {{7, 8, 9},
{10, 11, 12}};
int result[ROWS_A][COLS_B];
multiplyMatrices(matrixA, matrixB, result);
printf("Matrix A:\n");
printMatrix(matrixA, ROWS_A, COLS_A);
printf("\nMatrix B:\n");
printMatrix(matrixB, ROWS_B, COLS_B);
printf("\nResult Matrix:\n");
printMatrix(result, ROWS_A, COLS_B);
return 0;
}
In this program, we have two matrices matrixA and matrixB that we want to multiply. The multiplyMatrices() function takes the two matrices as input and performs the matrix multiplication, storing the result in the result matrix. It uses nested loops to iterate over the elements of the matrices and performs the necessary calculations using the formula for matrix multiplication.
The printMatrix() function is used to print the elements of a matrix in a formatted manner. It takes a matrix, the number of rows, and the number of columns as input and prints the elements row by row.
In the main() function, we define the matrices matrixA and matrixB with their respective dimensions. We also define the result matrix to store the result of the multiplication. We then call the multiplyMatrices() function, passing the input matrices and the result matrix. Finally, we print the original matrices and the resulting matrix using the printMatrix() function.
You can run this program to perform matrix multiplication with the provided matrices. Adjust the dimensions and values of the matrices as needed.
Note: The program assumes that the dimensions of the matrices are compatible for multiplication, i.e., the number of columns in matrixA matches the number of rows in matrixB.