How can I add up how many ints are even in the same array??

• 11-02-2011
caffrea4
How can I add up how many ints are even in the same array??
I'v only started to learn c++ this year so maybe this is just a simple problem.

here is the question I was given:

Write a function of the form int countEvens(int[], int) that returns the number of even ints in a given array, when passed the array and the number of elements in the array. Remember the % "mod" operator computes the remainder, e.g. 5 % 2 is 1.

countEvens({2, 1, 2, 3, 4},5) → 3
countEvens({2, 2, 0},3) → 3
countEvens({1, 3, 5},3) → 0

I passed the array and used the "mod" operator to identify which elements are even.

my problem is that I don't know how to add up how many even elements are in the array. Can anyone help me?

my code so far just displays which numbers in the array are even, I want to display how many are even. Here is my code

Code:

``` #include <cstdlib> #include <iostream> using namespace std; int countEvens(int a[], int size) {     int i;         for (i=0; i<size; i++)     {         if ((a[i]%2) == 0)         {           cout << a[i] << " is even" << endl;         }      }      }    int main() {     int array[5] = {2,3,4,5,2};     countEvens(array,5);         system("PAUSE");     return EXIT_SUCCESS; }```
• 11-02-2011
hk_mp5kpdw
Obviously you need a counter variable (initialized to 0) that you increment by 1 each time you get an even number. At the end of the function you return the value of this variable. When you call the function you must use the return value somehow, either print it directly or store the return value in another variable in your main function.
• 11-03-2011
Elysia
Is 0 odd ... or even? Or both?
• 11-03-2011
GReaper
Quote:

Originally Posted by Elysia
Is 0 odd ... or even? Or both?

Uhm, I guess you said it for a reason, but I have to say that:
Quote:

if n is zero or Natural

n*2 is Even
n*2 + 1 is Odd
:p