Advertisement
karbaev

matrix-mult

Mar 8th, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.82 KB | None | 0 0
  1. //Умножение матриц
  2. #include <iostream>
  3. using namespace std;
  4. int main()
  5. {
  6.     int a[10][10], b[10][10], mult[10][10], r1, c1, r2, c2, i, j, k;
  7.     cout << "Enter rows and columns for first matrix: ";
  8.     cin >> r1 >> c1;
  9.     cout << "Enter rows and columns for second matrix: ";
  10.     cin >> r2 >> c2;
  11.  
  12. /* If colum of first matrix in not equal to row of second matrix, asking user to enter the size of matrix again. */
  13.     while (c1!=r2)
  14.     {
  15.         cout << "Error! column of first matrix not equal to row of second.";
  16.         cout << "Enter rows and columns for first matrix: ";
  17.         cin >> r1 >> c1;
  18.         cout << "Enter rows and columns for second matrix: ";
  19.         cin >> r2 >> c2;
  20.     }
  21.  
  22. /* Storing elements of first matrix. */
  23.     cout << endl << "Enter elements of matrix 1:" << endl;
  24.     for(i=0; i<r1; ++i)
  25.     for(j=0; j<c1; ++j)
  26.     {
  27.         cout << "Enter element a" << i+1 << j+1 << " : ";
  28.         cin >> a[i][j];
  29.     }
  30.  
  31. /* Storing elements of second matrix. */
  32.     cout << endl << "Enter elements of matrix 2:" << endl;
  33.     for(i=0; i<r2; ++i)
  34.     for(j=0; j<c2; ++j)
  35.     {
  36.         cout << "Enter element b" << i+1 << j+1 << " : ";
  37.         cin >> b[i][j];
  38.     }
  39.  
  40. /* Initializing elements of matrix mult to 0.*/
  41.     for(i=0; i<r1; ++i)
  42.     for(j=0; j<c2; ++j)
  43.     {
  44.        mult[i][j]=0;
  45.     }
  46.  
  47. /* !!!Само умножение: Multiplying matrix a and b and storing in array mult. */
  48.     for(i=0; i<r1; ++i)
  49.     for(j=0; j<c2; ++j)
  50.     for(k=0; k<c1; ++k)
  51.     {
  52.         mult[i][j]+=a[i][k]*b[k][j];
  53.     }
  54.  
  55. /* Displaying the multiplication of two matrix. */
  56.     cout << endl << "Output Matrix: " << endl;
  57.     for(i=0; i<r1; ++i)
  58.     for(j=0; j<c2; ++j)
  59.     {
  60.         cout << " " << mult[i][j];
  61.         if(j==c2-1)
  62.             cout << endl;
  63.     }
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement