Hi,
Ok... Let's start by analysing your code, which is not bad.
Now, I do not understand the
int a[][2]
: it should be
int a[][MAX_COLUMNS]
, otherwise the loop won't be able to access all the content of the matrix or, worse, it can also access elements that are not part of the matrix. This is explained with
Pointer Arithmetics: a matrix is just an alias for a pointer of a pointer (int** a) which points to the element [0][0]. Whenever you try to access the next element in the same column ([1][0]), you just see the element pointed by the original pointer incremented by 1 * sizeof(int) = 2. [Reference:
Passing a 2D array to a C++ function - Stack Overflow[
^]]. The same conclusions can be drawn for the columns, but when you move to the next column ([0][1]), the compiler moves forward in memory by n_rows * 1 * sizeof(int). You can access the element [100][45] of a matrix that has been declared this way: int mx[10][10], but the element does not belong to the matrix, but it is in a completely different part of memory. Although it is not dangerous to read it, modifying it could be so because you are modifying a part of memory which, most likely, does not belong to your program. The program or the OS may crash and you'll be obliged to reboot your system.
Then, I do not see the usefulness of this line of code:
cout << "The even numbers are " << sum << endl;
If you return the value sum, what's the point in showing it to the user
each loop.
After that there is another thing I do not understand: does your task consist in counting even numbers or summing all the even numbers contained in the matrix together. Because the program you've written sums all the even numbers contained in the matrix and returns this sum. If you just want to count even numbers you should replace
sum = sum + a[i][j];
with
sum++;
Finally, it's the main program's duty to print out the result of the
Even
function, so you should "cout" it in the main.
To sum up, here's the code I would write to accomplish the task:
#include <iostream>
#define MAX_ROWS 3
#define MAX_COLUMNS 2
using namespace std;
int Even( int a[][MAX_COLUMNS], int length, int width){
int sum = 0;
int i;
int j;
for (i = 0; i < length, i++;){
for (j = 0; j < width, j++;){
if (a[i][j] % 2 == 0){
sum++;
}
}
}
return sum;
}
int main(){
int A[MAX_ROWS][MAX_COLUMNS] = { { 3, 2 }, { 4, 5 }, { 2, 2 } };
cout << "There are " << Even(A,MAX_ROWS,MAX_COLUMNS) << " even numbers in the matrix." << endl;
cout << "Goodbye :-)" << endl;
system("PAUSE");
return 0;
}