The following C code calculates the multiplication of two 2×2 matrices. The program prompts the user to input values for the first matrix and then asks for the values for the second matrix. It performs the matrix multiplication using nested for loops. The resulting matrix is then printed on the console. The code adheres to modern C programming standards, employing printf
and scanf
for input and output operations.
The outer loop iterates through each row of the first matrix, and another set of loops iterates through each column of the second matrix. During this process, the product of corresponding elements from the current row and column is accumulated to calculate the final value in the result matrix.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | #include <stdio.h> int main() { int mat1[2][2], mat2[2][2], mat3[2][2], i, j, k; // Input for the first matrix printf("Enter values for the first matrix:\n"); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { printf("Enter the value for row %d, column %d: ", i + 1, j + 1); scanf("%d", &mat1[i][j]); } } // Input for the second matrix printf("\nEnter values for the second matrix:\n"); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { printf("Enter the value for row %d, column %d: ", i + 1, j + 1); scanf("%d", &mat2[i][j]); } } // Displaying the given matrices printf("\nThe given matrices are:\n"); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { printf("%d\t", mat1[i][j]); } printf("\n"); } printf("\n"); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { printf("%d\t", mat2[i][j]); } printf("\n"); } // Matrix multiplication printf("\nThe multiplication of the matrices is:\n"); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { mat3[i][j] = 0; for (k = 0; k < 2; k++) { mat3[i][j] += mat1[i][k] * mat2[k][j]; } } } // Displaying the result for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { printf("%d\t", mat3[i][j]); } printf("\n"); } return 0; } |