Function which counts the even numbers in an array

For my computer science class I have to write a function that will count the even numbers in an array and for some reason my code is failing. I think it might have something to do with pointers.

1
2
3
4
5
6
7
8
9
10
int countEvens(int a[], int size) {
   int count = 0;
   
   for (int i = 0; i <= size-1; i++) {
      if (a[i]%2 == 0)
        count++;
    }

   return count;
}
Why doesn't it work for you? This works great for me (click the gear on the right side of code to run it on cpp.sh site):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>

int countEvens(int a[], int size) {
	int count = 0;

	for (int i = 0; i <= size - 1; i++) {
		if (a[i] % 2 == 0)
			count++;
	}

	return count;
}

int main() {
	int a[5]{2, 3, 4, 4, 1};
	std::cout << countEvens(a, 5);
	std::cin.get();
	return 0;
} 
Last edited on
Topic archived. No new replies allowed.