Issue calling counter loop function in main

Hello, I am currently stuck and unable to get the proper results for my program. Part of the assignment is to count and print all even numbers from an array. I have built my code but just this function doesn't seem to be working right. I am not sure if it's my function call in main that has the problem or the function countEvens itself. When I run this it always shows the count as 0. Please help

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
#include <iostream>
#include <ctime>

using namespace std;

void fillArray(int arr[], int size);
void printArray(int arr[], int size);
int countEvens(int arr[], int size);


int main()
{
	srand(time(0));

	const int size = 25;
	int ar[size];

	resetArray(ar, size);

	cout << "Printing the array" << endl;

	fillArray(ar, size);//insert fillArray function
	printArray(ar, size);//insert printArray function

	cout << "Even numbers occur: " << countEvens(ar, size) << " times" << endl;

	return 0;
}


void fillArray(int arr[], int size)
{
	for (int i = 0; i < size; i++)
	{
		arr[i] = rand() % 100 + 1;
	}
}

void printArray(int arr[], int size)
{
	for (int i = 0; i < size; i++)
	{
		cout<< arr[i]<< endl;
	}
}

int countEvens(int arr[], int size)
{
	int count = 0;
	int evens = 0;
	for (int i = 0; i < size; i++)
	{
		if (arr[i] % 2 == evens)
		{
			count++;
		}
		return count;
	}
}



Printing the array
23
88
85
30
21
59
60
12
10
2
100
37
33
82
97
63
15
91
76
45
4
85
57
26
8
Even numbers occur: 0 times
Press any key to continue . . .
Last edited on
On function countevents():

Leave line ‘return count ‘ from for loop
Because stop the loop at first iteration
Last edited on
I removed the line (57) but now it's throwing an error saying I must have a return value. So, I changed the function to be

void countEvens() and updated the prototype to match

but now that is also throwing a bunch of other errors....

I feel like ive tried all sorts of variations but I just can't get it.
Last edited on
remove the return from the for loop and place it before the closing bracket of the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
int countEvens(int arr[], int size)
{
	int count = 0;
	int evens = 0;
	for (int i = 0; i < size; i++)
	{
		if (arr[i] % 2 == evens)
		{
			count++;
		}
	}
	return count;
}


Also, to get rid of the other error, which likely has to do with:

resetArray(ar, size);

You still have to write the according function, or delete it entirely, as there does not seem to be any use for it.
@Misenna - that was it!! My the program is working perfectly now. I knew it was going to come down to something silly.

Thank you so much ar2007 and Misenna I truly appreciate your help. I've only been working on this code for like 3 days, haha.
Topic archived. No new replies allowed.