In this tutorial, we will learn and write a C++ program to print the subtraction of two matrices. To understand the coding, you should have knowledge of the following topics in **C++ programming**:

The program takes the user input for the number of rows and columns and then the elements for both the matrices.

Lastly, subtract the matrices and store them in a separate array and display the result. Let us go through the program.

**C++ Program to Subtract Two Matrices**

During the subtraction of matrices, it is important that both of the matrices should have the same dimensions such as the 2×3 matrix can be subtracted only with a 2×3 matrix.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #include <iostream> using namespace std; int main() { int arr1[50][50], arr2[50][50], sub[50][50]; int row, col, i, j; cout << "Enter the no. of rows: "; cin >> row; cout << "Enter the no. of columns: "; cin >> col; // 1st matrix user input cout << endl << "Enter 1st Matrix elements: " << endl; for (i = 0; i < row; ++i) for (j = 0; j < col; ++j) cin >> arr1[i][j]; // 2nd matrix user input cout << endl << "Enter 2nd Matrix elements: " << endl; for (i = 0; i < row; ++i) for (j = 0; j < col; ++j) cin >> arr2[i][j]; // matrix adition for (i = 0; i < row; ++i) for (j = 0; j < col; ++j) sub[i][j] = arr1[i][j] - arr2[i][j]; // Displaying the result cout << endl << "Result of the subtraction of the matrices: " << endl; for (i = 0; i < row; ++i) for (j = 0; j < col; ++j) { cout << sub[i][j] << " "; if (j == col - 1) cout << endl; } return 0; } |

**Output:**

`Enter the no. of rows: 2`

Enter the no. of columns: 3

Enter 1st Matrix elements:

6

5

4

3

2

1

Enter 2nd Matrix elements:

3

2

3

3

1

1

Result of the subtraction of the matrices:

3 3 1

0 1 0