1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
|
#include <iostream>
#include <cstdlib>
#define SIZE 3
using namespace std;
/*Write a function that takes two, 2-dimensional arrays as arguments.
The function should ensure they are the same size and then print to the
screen an array created by summing the elements in each array that are
in the same row and column as in the example below.
1 2 3 2 4 6 3 6 9
4 5 6 + 2 2 3 = 6 7 9
1 2 3 3 7 1 4 9 4
*/
//declare matrix addition function
int MatrixAdd (int matrix1[][SIZE], int matrix2[][SIZE]);
//populate two, 2d matrices, print to the screen
int main (void)
{
int myarray1 [SIZE][SIZE] = {
{1,1,1},
{2,2,2},
{3,3,3},
};
int myarray2 [SIZE][SIZE] = {
{1,1,1},
{2,2,2},
{3,3,3},
};
for (int i = 0; i < SIZE ; i++)
{
for (int j = 0; j < SIZE; j++)
{
cout << myarray1 [i][j] << "\t";
}
cout << endl;
}
cout << endl;
for (int i = 0; i < SIZE ; i++)
{
for (int j = 0; j < SIZE; j++)
{
cout << myarray2 [i][j] << "\t";
}
cout << endl;
}
//function call
cout << MatrixAdd (myarray1, myarray2) << endl;
return 1;
}
//matrix addition function
int MatrixAdd (int* matrix1, int* matrix2)
{
//ensure matrices are of equal size
if( SIZE < 2 )
{
cout << "Error: Array too small" << endl;
return 1;
}
//create a third matrix for the matrices to be added into
int Matrix3 [SIZE][SIZE];
for (int i = 0; i < SIZE ; i++)
{
for (int j = 0; j < SIZE; j++)
{
Matrix3 [i][j] = (matrix1, int SIZE + matrix2, int SIZE);
cout << Matrix3 [i][j] << "\t";
}
cout << endl;
}
cout << endl;
return (Matrix3[SIZE][SIZE]);
}
|