In this post, you will learn ** how to Add Two Matrices Using Multi-dimensional Arrays** using

**.**

*C++*This lesson will teach you how to Add Two Matrices Using Multi-dimensional Arrays, using mathematical function, and the for loop statement using the C++ Language. Letâ€™s look at the below source code.

## How to Add Two Matrices Using Multi-dimensional Arrays?

RUN CODE SNIPPET## Source Code

#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

The statementsÂ **#include<iostream>, using namespace std, int main**Â are the main factors that **support** the function of the source code.

Now we can look into the working and layout of the codeâ€™s function.

- Initialize theÂ
**variables***r, c, sum, i, j, a, bÂ*as**integersÂ**and assign the variables*r and cÂ*with the values to be calculated and declare the variablesÂ*sum, aÂ*andÂ*bÂ*asÂ**arrays.** - Assign the values for theÂ
**arrays a and bÂ**using the curly bracesÂ**{ }.**Using the output functionÂ**coutÂ**display the firstÂ**array.** - Declare aÂ
**for loopÂ**with the condition`(i=0; i<r; ++i)`

and in the body of the loop declare anotherÂ**for loopÂ**with the condition`(j=0; j<c; ++j)`

with the output statement to display the arrayÂ**a.** - The aboveÂ
**nested for loopÂ**is used to display the firstÂ**array.Â**This is followed by a similar section of code to display the secondÂ**array.** - Next declare twoÂ
**for loopsÂ**to verify the values in the array, and insert the following mathematical function to find theÂ**sum of the two arrays**`sum[i][j]=a[i][j]+b[i][j]`

. - Using theÂ
**for loop**and theÂ**coutÂ**function display the sum of the two arrays as the answer. - In each nested
**for loop**the first condition verifies the size of the loop, that is it checks the size of the**row**and the**column,**where the assigned size of the row and the column must be similar to the**size**of the**row**and**column**of the**arrays**and the second condition verifies the elements in the array.