## Matrix addition 2D with pre-initialised values

Adding two 2D integer matrix into a third matrix of same size with values pre-initialised at the beginning.

## Learning Objectives

- 2D Matrix initialisation
- Matrix addition into a target matrix of same size.
- Retrieving data from a 2D matrix and printing in a matrix fashion only.

## Source Code

`#include <iostream>`

using namespace std;

int main()

{

int A[2][3]={{1,2,3},{4,5,6}};

int B[2][3]={{7,8,9},{10,11,12}};

int C[2][3];

for(int i=0 ; i<2 ; i++ )

{

for(int j=0; j<3; j++ )

{

C[i][j]=A[i][j]+B[i][j];

}

}

for(int i=0 ; i<2 ; i++ )

{

for(int j=0; j<3; j++ )

{

cout<<C[i][j]<<"t";

}

cout<<endl;

}

return 0;

}

## Run Output

## Code Understanding

** int A[2][3]={{1,2,3},{4,5,6}};**

** int B[2][3]={{7,8,9},{10,11,12}};**

** int C[2][3];**

A & B are 2 row three column integer matrix with values initialised as given. C is a matrix of same size as A and B but without any initial values. This will contain the sum of values of A and B at the corresponding postions.

**for(int i=0 ; i<2 ; i++ )** //Row traversing loop

**{**

**for(int j=0; j<3; j++ )** //column traversing loop

**{**

**C[i][j]=A[i][j]+B[i][j];** **//**Adding A & B corresponding member in putting in C

**}**

**}
**

**This one is the loop for printing the final matrix.**

//

//

**for(int i=0 ; i<2 ; i++ ) { for(int j=0; j<3; j++ ) {**

**cout<<C[i][j]<<“t”;**//here individual items of each row are printed with tab character in between.

**} cout<<endl;**// //here a line between two rows are printed.

**}**

## Notes

A check for target matrix meeting the condition of addability of two matrix can also be done.

**Suggested Filename(s): **addmatrix.cpp, matrixadditioninit.cpp

sunmitra| Created: 5-Dec-2017 | Updated: 8-Dec-2017|