C++ gurus and learners, we program ourselves :P all work is CC licensed

Sunday, November 17

Addition of two 2-Dimensional Arrays

Below is the code that I made to add the elements of a 2-D array.
The 2-dimensional arrays have been previously discussed, what they are and how to initialize them.
http://cppqa.blogspot.com/2013/11/two-dimension-pointers-c.html

For those (like me) who are still confused, think of it like this,
An 1-dimensional array can hold element like this:
[ 1 3 5 7 9]    => array1[5]

Whereas a 2-D array will hold elements much like a matrix, like this:
| 2  4 |
| 6  8 |            => array2[2][2]
So we get a matix of 2rows and 2 columns.

Now that we have a basic concept of 2-D array, lets go a little further.
The initialization is petty much same as that in the above link. We shall only do the addition of 2-D arrays.

int main()
{
int x[2][2] , y[2][2] , z[2][2];
//for simplicity 2,2 matrix is used, but you can also make a user specified

int i , j , k;

cout<<"enter number for 1st matrix"<<endl; //applying for loop to enter the data

for( i = 0 ; i < 2 ; i++)
for( j = 0 ; j < 2 ; j++)
{
cin>>x[i][j];
}
 
cout<<"enter numbers for 2nd matrix"<<endl;
for( i = 0 ; i < 2 ; i++)
for( j = 0 ; j < 2 ; j++)
{
cin>>y[i][j];
}

for( i = 0 ; i < 2 ; i++)
for( j = 0 ; j < 2 ; j++)
{
z[i][j] = 0;
for( k = 0 ;k < 2 ; k++)
z[i][j]=x[i][j]+y[i][j]; // x + y stored in z
}

cout<<"additon of matrix is"<<endl;   // z is displayed
for( i = 0 ; i < 2 ; i++)
{
for( j = 0 ; j < 2 ; j++)
cout<<z[i][j]<<"\t";
cout<<"\n";
}
getch();
return 0;
}

So here it is a simple program to add two 2-D arrays

1 comments :