This is a C++ Program to Demonstrate Matrix Addition.
The program adds two matrices and prints the resultant output.
1. The program checks the number of rows and columns of the two matrices.
2. If they are not equal, the matrices cannot be added and the program is exited.
3. Else the matrices are added using for loops.
4. The resultant matrix is then printed.
5. Exit.
Here is the source code of C++ Program to Add Two Matrices and Print the Output. The program output is shown below.
#include<iostream>
using namespace std;
int main ()
{
int m, n, p, q, i, j, A[5][5], B[5][5], C[5][5];
cout << "Enter rows and column of matrix A : ";
cin >> m >> n;
cout << "Enter rows and column of matrix B : ";
cin >> p >> q;
if ((m != p) && (n != q))
{
cout << "Matrices cannot be added!";
exit(0);
}
cout << "Enter elements of matrix A : ";
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
cin >> A[i][j];
cout << "Enter elements of matrix B : ";
for (i = 0; i < p; i++)
for (j = 0; j < q; j++)
cin >> B[i][j];
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
C[i][j] = A[i][j] + B[i][j];
cout << "Sum of matrices\n";
for (i = 0; i < m; i++)
{ for (j = 0; j < n; j++)
cout << C[i][j] << " ";
cout << "\n";
}
return 0;
}
1. The user is initially asked to enter the number of rows and columns of both the matrices.
2. If number of rows and columns of matrix A are not equal to number of rows and columns of matrix B respectively, then matrices cannot be added. The program is exited.
3. Else if they are equal, the elements of both the matrices are entered and added.
4. The resultant matrix C is then printed.
Case 1 : Enter rows and column of matrix A : 2 2 Enter rows and column of matrix B : 2 2 Enter elements of matrix A : 1 2 3 4 Enter elements of matrix B : 4 3 2 1 Sum of matrices 5 5 5 5 Case 2 : Enter rows and column of matrix A : 2 3 Enter rows and column of matrix B : 3 2 Matrices cannot be added! Case 3 : Enter rows and column of matrix A : 1 3 Enter rows and column of matrix B : 1 3 Enter elements of matrix A : 0 2 7 Enter elements of matrix B : 0 3 3 Sum of matrices 0 5 10
Sanfoundry Global Education & Learning Series – C++ Programs.
To practice all C++ programs, here is complete set of 1000+ C++ Programming examples.
- Check Programming Books
- Apply for Computer Science Internship
- Apply for C++ Internship
- Check Computer Science Books
- Practice Computer Science MCQs