Write a C++ Program to add two Matrixes with an example. In this C++ matrix addition example, we used the C++ nested for loop to iterate addarr1 and addarr2 matrixes from 0 to rows and columns. Within the nested for loop, we performed addition on both the matrixes and assigned them to the addition matrix.
(addition[rows][columns] = addarr1[rows][columns] + addarr2[rows][columns];)
Finally, we used one more nested for loop to print the addition matrix items.
#include<iostream>
using namespace std;
int main()
{
int i, j, rows, columns;
cout << "\nPlease Enter the rows and Columns a Multi-Dimensional Array = ";
cin >> i >> j;
int addarr1[i][j], addarr2[i][j], addition[i][j];
cout << "\nPlease Enter the First Multi-Dimensional Array Items = ";
for(rows = 0; rows < i; rows++) {
for(columns = 0; columns < i; columns++) {
cin >> addarr1[rows][columns];
}
}
cout << "\nPlease Enter the Second Multi-Dimensional Array Items = ";
for(rows = 0; rows < i; rows++) {
for(columns = 0; columns < i; columns++) {
cin >> addarr2[rows][columns];
}
}
for(rows = 0; rows < i; rows++) {
cout << "\n---The Addition Result of " << rows + 1 << " Row Iteration---\n";
for(columns = 0; columns < j; columns++) {
addition[rows][columns] = addarr1[rows][columns] + addarr2[rows][columns];
cout << "\nThe Addition Result of " << columns + 1 << " Column Iteration = ";
cout << addarr1[rows][columns] << " + " << addarr2[rows][columns] << " = " << addition[rows][columns] << "\n";
}
}
cout << "\nThe Final Result after adding addarr1 & addarr2 \n ";
for(rows = 0; rows < i; rows++) {
for(columns = 0; columns < j; columns++) {
cout << addition[rows][columns] << " ";
}
cout<<"\n";
}
return 0;
}
C++ Program to Add Two Matrixes Example 2
In this C++ matrix addition example, we removed that extra for loop to display the items and placed a cout statement (cout << addition[rows][columns] << ” “;) after performing the addition.
#include<iostream>
using namespace std;
int main()
{
int i, j, rows, columns;
cout << "\nPlease Enter the rows and Columns a Multi-Dimensional Array = ";
cin >> i >> j;
int addarr1[i][j], addarr2[i][j], addition[i][j];
cout << "\nPlease Enter the First Multi-Dimensional Array Items = ";
for(rows = 0; rows < i; rows++) {
for(columns = 0; columns < i; columns++) {
cin >> addarr1[rows][columns];
}
}
cout << "\nPlease Enter the Second Multi-Dimensional Array Items = ";
for(rows = 0; rows < i; rows++) {
for(columns = 0; columns < i; columns++) {
cin >> addarr2[rows][columns];
}
}
cout << "\nThe Final Result after adding addarr1 & addarr2\n";
for(rows = 0; rows < i; rows++) {
for(columns = 0; columns < j; columns++) {
addition[rows][columns] = addarr1[rows][columns] + addarr2[rows][columns];
cout << addition[rows][columns] << " ";
}
}
return 0;
}