A matrix is a rectangular array of numbers that is arranged in the form of rows and columns.
An example of a matrix is as follows.
A 4*3 matrix has 4 rows and 3 columns as shown below −
3 5 1 7 1 9 3 9 4 1 6 7
A program that adds two matrices using multidimensional arrays is as follows.
Example
#include <iostream>
using namespace std;
int main() {
int r=2, c=4, sum[2][4], i, j;
int a[2][4] = {{1,5,9,4} , {3,2,8,3}};
int b[2][4] = {{6,3,8,2} , {1,5,2,9}};
cout<<"The first matrix is: "<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
cout<<"The second matrix is: "<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<b[i][j]<<" ";
cout<<endl;
}
cout<<endl;
for(i=0;i<r;++i)
for(j=0;j<c;++j)
sum[i][j]=a[i][j]+b[i][j];
cout<<"Sum of the two matrices is:"<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<sum[i][j]<<" ";
cout<<endl;
}
return 0;
}Output
The first matrix is: 1 5 9 4 3 2 8 3 The second matrix is: 6 3 8 2 1 5 2 9 Sum of the two matrices is: 7 8 17 6 4 7 10 12
In the above program, first the two matrices a and b are defined. This is shown as follows.
int a[2][4] = {{1,5,9,4} , {3,2,8,3}};
int b[2][4] = {{6,3,8,2} , {1,5,2,9}};
cout<<"The first matrix is: "<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
cout<<"The second matrix is: "<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<b[i][j]<<" ";
cout<<endl;
}The two matrices are added using a nested for loop and the result is stored in matrix sum[][]. This is shown in the following code snippet.
for(i=0;i<r;++i) for(j=0;j<c;++j) sum[i][j]=a[i][j]+b[i][j];
After the sum of the two matrices is obtained, it is printed on screen. This is done as follows −
cout<<"Sum of the two matrices is:"<<endl;
for(i=0; i<r; ++i) {
for(j=0; j<c; ++j)
cout<<sum[i][j]<<" ";
cout<<endl;
}