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