C Program to Multiply two Matrices using Recursion !!
Introduction :
[arrowlist]
- We can multiply 2 matrices without using function.
- Visit this article to know Detailed Steps for Matrix Multiplication.
[/arrowlist]
Visual Representation :
1 | <a href="https://www.c4learn.com/2011/12/matrix_multiplication1.png"><img src="https://www.c4learn.com/2011/12/matrix_multiplication1.png" alt="" width="320" height="148" class="aligncenter size-full wp-image-2670" /></a> |
Program :
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | #include<stdio.h> #define MAX 10 void matrixMultiply(int[MAX][MAX], int[MAX][MAX]); int row1, row2, col1, col2; int res[MAX][MAX]; int main() { int mat1[MAX][MAX], mat2[MAX][MAX], i, j, k; printf("Enter the row and column of first matrix: "); scanf("%d%d", &row1, &col1); printf("Enter the row and column of second matrix: "); scanf("%d%d", &row2, &col2); if (col1 != row2) { printf("Matrix multiplication is not possible"); } else { printf("Enter the First matrix: "); for (i = 0; i < row1; i++) { for (j = 0; j < col1; j++) { scanf("%d", &mat1[i][j]); } } printf("Enter the Second matrix: "); for (i = 0; i < row2; i++) { for (j = 0; j < col2; j++) { scanf("%d", &mat2[i][j]); } } printf("\nThe First matrix is: n"); for (i = 0; i < row1; i++) { printf("\n"); for (j = 0; j < col1; j++) { printf("%d ", mat1[i][j]); } } printf("\nThe Second matrix is: n"); for (i = 0; i < row2; i++) { printf("\n"); for (j = 0; j < col2; j++) { printf("%d ", mat2[i][j]); } } matrixMultiply(mat1, mat2); } printf("\nThe multiplication of two matrixes is : \n"); for (i = 0; i < row1; i++) { printf("\n"); for (j = 0; j < col2; j++) { printf("%d ", res[i][j]); } } return 0; } void matrixMultiply(int a[MAX][MAX], int b[MAX][MAX]) { static int sum, i = 0, j = 0, k = 0; //row of first matrix if (i < row1) { //column of second matrix if (j < col2) { if (k < col1) { sum = sum + a[i][k] * b[k][j]; k++; matrixMultiply(a, b); } res[i][j] = sum; sum = 0; k = 0; j++; matrixMultiply(a, b); } j = 0; i++; matrixMultiply(a, b); } } |
output :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Enter the row and column of first matrix: 2 2 Enter the row and column of second matrix: 2 2 Enter the First matrix: 1 2 3 4 Enter the Second matrix: 1 2 1 2 The First matrix is: 1 2 3 4 The Second matrix is: 1 2 1 2 The multiplication of two matrixes is: 3 6 7 14 |
How to Verify Multiplication ?
Visit This External Tool Which Will Calculate Multiplication of Two Matrices