Header Ads Widget

Ticker

6/recent/ticker-posts

Matrix multiplication in C++ Notes+Coding by Digitalise Data

 

Matrix multiplication in C++ Notes+Coding by Digitalise Data

Matrix multiplication in C++

We can add, subtract, multiply and divide 2 matrices. To do so, we are taking input from the user for row number, column number, first matrix elements and second matrix elements. Then we are performing multiplication on the matrices entered by the user.

In matrix multiplication first matrix one row element is multiplied by second matrix all column elements.

Let's try to understand the matrix multiplication of 3*3 and 3*3 matrices by the figure given below:

Matrix multiplication in C++ Notes+Coding by Digitalise Data

Let's see the program of matrix multiplication in C++.

  1. #include <iostream.h>
  2. #include <conio.h>
  3. void main()  
  4. {  
  5. int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;    
  6. cout<<"enter the number of row=";    
  7. cin>>r;    
  8. cout<<"enter the number of column=";    
  9. cin>>c;    
  10. cout<<"enter the first matrix element=\n";    
  11. for(i=0;i<r;i++)    
  12. {    
  13. for(j=0;j<c;j++)    
  14. {    
  15. cin>>a[i][j];  
  16. }    
  17. }    
  18. cout<<"enter the second matrix element=\n";    
  19. for(i=0;i<r;i++)    
  20. {    
  21. for(j=0;j<c;j++)    
  22. {    
  23. cin>>b[i][j];    
  24. }    
  25. }    
  26. cout<<"multiply of the matrix=\n";    
  27. for(i=0;i<r;i++)    
  28. {    
  29. for(j=0;j<c;j++)    
  30. {    
  31. mul[i][j]=0;    
  32. for(k=0;k<c;k++)    
  33. {    
  34. mul[i][j]+=a[i][k]*b[k][j];    
  35. }    
  36. }    
  37. }    
  38. //for printing result    
  39. for(i=0;i<r;i++)    
  40. {    
  41. for(j=0;j<c;j++)    
  42. {    
  43. cout<<mul[i][j]<<" ";    
  44. }    
  45. cout<<"\n";    
  46. }    
  47. getch ();  
  48. }    

Output:

enter the number of row=3  
enter the number of column=3  
enter the first matrix element= 
1 2 3
1 2 3  
1 2 3       
enter the second matrix element= 
1 1 1  
2 1 2   
3 2 1    
 multiply of the matrix=  
14 9 8      
14 9 8  
14 9 8

Post a Comment

0 Comments