» » » Matrix multiplication in c program with explanation

# Matrix multiplication in c program with explanation

• Matrix multiplication in c.
• Take three two dimensional arrays
• int first_matrix[10][10], second_matrix[10][10], multiply_result[10][10];
• Two for take input from user for matrices one for capture multiplication of two matrices result.
• Ask user to enter number of columns of rows of first matrix.  m ,n
• Read from keyboard using scanf() function in java. and store all the elements (rows*columns) in first matrix using two for loops.
• Ask user to enter number of columns of rows of second matrix. p , q
• Read from keyboard using scanf() function in java. and store all the elements (rows*columns) in first matrix using two for loops.
• Now take two more loops for rows of first matrix and columns of second matrix.
• Third for loop for multiplication iteratek
• for (c = 0; c < m; c++) {
•       for (d = 0; d < q; d++) {
•         for (k = 0; k < p; k++) {
•           sum = sum + first_matrix[c][k]*second_matrix[k][d];
•         }
•
•         multiply_result[c][d] = sum;
•         sum = 0;
•       }
•     }
• c program for multiplication of two matrices using arrays

Program #1: Write a c program to multiply two matrices. c program for matrix multiplication using arrays

1. #include <stdio.h>
2. #include <stdlib.h>
3.
4. int main()
5. {
6.   int m, n, p, q, c, d, k, sum = 0;
7.   int first_matrix[10][10], second_matrix[10][10], multiply_result[10][10];
8.
9.   printf("Enter the number of rows and columns of first matrix\n");
10.   scanf("%d%d", &m, &n);
11.   printf("Enter the elements of first matrix\n");
12.    for (c = 0; c < m; c++)
13.    for (d = 0; d < n; d++)
14.       scanf("%d", &first_matrix[c][d]);
15.
16.   printf("Enter the number of rows and columns of second matrix\n");
17.   scanf("%d%d", &p, &q);
18.
19.   if (n != p)
20.     printf("Matrices with entered orders can't be multiplied with each other.\n");
21.   else
22.   {
23.     printf("Enter the elements of second matrix\n");
24.
25.     for (c = 0; c < p; c++)
26.       for (d = 0; d < q; d++)
27.         scanf("%d", &second_matrix[c][d]);
28.
29.     for (c = 0; c < m; c++) {
30.       for (d = 0; d < q; d++) {
31.         for (k = 0; k < p; k++) {
32.           sum = sum + first_matrix[c][k]*second_matrix[k][d];
33.         }
34.
35.         multiply_result[c][d] = sum;
36.         sum = 0;
37.       }
38.     }
39.
40.     printf("Product of entered matrices:-\n");
41.
42.     for (c = 0; c < m; c++) {
43.       for (d = 0; d < q; d++)
44.         printf("%d\t", multiply_result[c][d]);
45.
46.       printf("\n");
47.     }
48.   }
49.
50.  getch();
51. }

Output: