 # C++ Programming Code Examples

## C++ > Arrays and Matrices Code Examples

### Program to Multiply Two Matrix Using Multi-dimensional Arrays

``` Program to Multiply Two Matrix Using Multi-dimensional Arrays This program takes two matrices of order r1*c1 and r2*c2 respectively. Then, the program multiplies these two matrices (if possible) and displays it on the screen. To multiply two matrices, the number of columns of first matrix should be equal to the number of rows to second matrix. This program displays the error until the number of columns of first matrix is equal to the number of rows of second matrix. In this program, user is asked to enter the size of two matrix at first. The column of first matrix should be equal to row of second matrix for multiplication. If this condition is not satisfied then, the size of matrix is again asked using while loop. Then, user is asked to enter two matrix and finally the output of two matrix is calculated and displayed. Since, the program is long and hard to debug, it is better to solve this program by passing it to a function. #include <iostream> using namespace std; int main() { int a, b, mult, r1, c1, r2, c2, i, j, k; cout << "Enter rows and columns for first matrix: "; cin >> r1 >> c1; cout << "Enter rows and columns for second matrix: "; cin >> r2 >> c2; // If column of first matrix in not equal to row of second matrix, // ask the user to enter the size of matrix again. while (c1!=r2) { cout << "Error! column of first matrix not equal to row of second."; cout << "Enter rows and columns for first matrix: "; cin >> r1 >> c1; cout << "Enter rows and columns for second matrix: "; cin >> r2 >> c2; } // Storing elements of first matrix. cout << endl << "Enter elements of matrix 1:" << endl; for(i = 0; i < r1; ++i) for(j = 0; j < c1; ++j) { cout << "Enter element a" << i + 1 << j + 1 << " : "; cin >> a[i][j]; } // Storing elements of second matrix. cout << endl << "Enter elements of matrix 2:" << endl; for(i = 0; i < r2; ++i) for(j = 0; j < c2; ++j) { cout << "Enter element b" << i + 1 << j + 1 << " : "; cin >> b[i][j]; } // Initializing elements of matrix mult to 0. for(i = 0; i < r1; ++i) for(j = 0; j < c2; ++j) { mult[i][j]=0; } // Multiplying matrix a and b and storing in array mult. for(i = 0; i < r1; ++i) for(j = 0; j < c2; ++j) for(k = 0; k < c1; ++k) { mult[i][j] += a[i][k] * b[k][j]; } // Displaying the multiplication of two matrix. cout << endl << "Output Matrix: " << endl; for(i = 0; i < r1; ++i) for(j = 0; j < c2; ++j) { cout << " " << mult[i][j]; if(j == c2-1) cout << endl; } return 0; } ``` 