Advertisement
Guest User

Untitled

a guest
Oct 18th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int main() {
  4. int n1,m1,n2,m2;
  5.  
  6. printf("How many rows will first matrix have?\n");
  7. scanf("%d", &n1);
  8. printf("How many columns will first matrix have?\n");
  9. scanf("%d", &m1);
  10. printf("How many rows will second matrix have?\n");
  11. scanf("%d", &n2);
  12. printf("How many columns will second matrix have?\n");
  13. scanf("%d", &m2);
  14.  
  15. // check the condition to multiply matrices
  16. if(m1 != n2){
  17. printf("Bad dimensions.");
  18. return 0;
  19. }
  20.  
  21. int ar1[n1][m1], ar2[n2][m2], res[n1][m2];
  22.  
  23. printf("Provide numbers in the first matrix: \n");
  24.  
  25. for(int i = 0; i < n1; ++i){
  26. for(int j = 0; j < m1; ++j)
  27. scanf("%d", &ar1[i][j]);
  28. }
  29.  
  30. printf("Provide numbers in the second matrix: \n");
  31.  
  32. for(int i = 0; i < n2; ++i){
  33. for(int j = 0; j < m2; ++j)
  34. scanf("%d", &ar2[i][j]);
  35. }
  36.  
  37. //initialize whole result array to 0
  38. for(int i = 0; i < n1; ++i)
  39. for(int j = 0; j < m2; ++j)
  40. res[i][j] = 0;
  41.  
  42. //multiply first and second matrix and store the value into result array
  43. for(int i = 0; i < n1; ++i)
  44. {
  45. for(int j = 0; j < m2; ++j)
  46. {
  47. for(int k=0; k < m1; ++k)
  48. {
  49. res[i][j] += ar1[i][k] * ar2[k][j];
  50. }
  51. }
  52. }
  53.  
  54. //display the result
  55. printf("\nFinal matrix: \n");
  56. for(int i = 0; i < n1; ++i) {
  57. for (int j = 0; j < m2; ++j) {
  58. printf("%d", res[i][j]);
  59. printf("\t");
  60. }
  61. printf("\n");
  62. }
  63.  
  64.  
  65. return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement