Write C++ Program to Multiply Two Matrices


I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


techstudy.org

HP 15 Core i3 7th gen Laptop(4GB, 1TB HDD, Windows 10) | Rs. 31,490

Introduction

I have used CodeBlocks compiler for debugging purpose. But you can use any C++ programming language compiler as per your availability.


  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main()
  5. {
  6. int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k;
  7.  
  8. cout<<"Enter rows and column for first matrix: ";
  9. cin>>r1;
  10. cin>>c1;
  11.  
  12. cout<<"Enter rows and column for second matrix: ";
  13. cin>>r2;
  14. cin>>c2;
  15.  
  16. // Column of first matrix should be equal to column of second matrix and
  17. while (c1 != r2)
  18. {
  19. cout<<"Error! column of first matrix not equal to row of second.\n\n";
  20. cout<<"Enter rows and column for first matrix: ";
  21. cin>>r1;
  22. cin>>c1;
  23. cout<<"Enter rows and column for second matrix: ";
  24. cin>>r2;
  25. cin>>c2;
  26. }
  27.  
  28. // Storing elements of first matrix.
  29. cout<<"\nEnter elements of matrix 1:\n";
  30. for(i=0; i<r1; ++i)
  31. for(j=0; j<c1; ++j)
  32. {
  33. cout<<"Enter element a"<<i+1<<j+1<<": ";
  34. cin>>a[i][j];
  35. }
  36.  
  37. // Storing elements of second matrix.
  38. cout<<"\nEnter elements of matrix 2:\n";
  39. for(i=0; i<r2; ++i)
  40. for(j=0; j<c2; ++j)
  41. {
  42. cout<<"Enter element b"<<i+1<<j+1<<": ";
  43. cin>>b[i][j];
  44. }
  45.  
  46. // Initializing all elements of result matrix to 0
  47. for(i=0; i<r1; ++i)
  48. for(j=0; j<c2; ++j)
  49. {
  50. result[i][j] = 0;
  51. }
  52.  
  53. // Multiplying matrices a and b and
  54. // storing result in result matrix
  55. for(i=0; i<r1; ++i)
  56. for(j=0; j<c2; ++j)
  57. for(k=0; k<c1; ++k)
  58. {
  59. result[i][j]+=a[i][k]*b[k][j];
  60. }
  61.  
  62. // Displaying the result
  63. cout<<"\nOutput Matrix:\n";
  64. for(i=0; i<r1; ++i)
  65. for(j=0; j<c2; ++j)
  66. {
  67. cout<<" "<<result[i][j];
  68. if(j == c2-1)
  69. cout<<"\n\n";
  70. }
  71. return 0;
  72. }
  73.  

Result

C++ language techstudy.org

     





Related Topics




Popular Posts