This C++ Program which demonstrates subtraction of two matrices of same order. The program initializes the matrices, subtracts each corresponding element of the two matrices and puts the value in the third matrix.
Here is source code of the C++ program which demonstrates subtraction of two matrices of same order. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C++ program to demonstrate matrix subtraction
*/
#include<iostream>
using namespace std;
int main()
{
int mat1[3][3], mat2[3][3], mat3[3][3];
/* Initializing Mat1 and Mat2 */
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
mat1[i][j] = i + 1;
mat2[i][j] = j + 1;
}
}
/* Adding matrices Mat1 and Mat2 */
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
mat3[i][j] = mat2[i][j] - mat1[i][j];
}
}
cout << "First Matrix : " << endl;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << mat1[i][j] << "\t";
}
cout << endl;
}
cout << "Second Matrix : " << endl;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << mat2[i][j] << "\t";
}
cout << endl;
}
cout << "Third Matrix = Second Matrix - First Matrix : " << endl;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
cout << mat3[i][j] << "\t";
}
cout << endl;
}
}
$ g++ main.cpp $ ./a.out First Matrix : 1 1 1 2 2 2 3 3 3 Second Matrix : 1 2 3 1 2 3 1 2 3 Third Matrix = Second Matrix - First Matrix : 0 1 2 -1 0 1 -2 -1 0
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.
If you find any mistake above, kindly email to [email protected]Related Posts:
- Apply for Computer Science Internship
- Practice Computer Science MCQs
- Check C++ Books
- Practice Programming MCQs
- Check Programming Books