Creating a function that totals the odd numbers and totals the even numbers stored in an array.

I am a C++ beginner and need assistance solving this problem. I have tried hundreds of different ideas but I can't seem to get it to take the numbers from the array as input and separate the odd and even numbers. This is what I have so far, I need help on how to go about sorting and totaling the number of odd and even numbers. Thank you for any input you have!




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

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <conio.h>

using namespace std;
void format();
void print_array(int[],const int);
void calc_average(int[],const int, double&);

int main()
{
	const int arraysize = 10;
	int num_arr[arraysize] = {0};
	double average = 0.0;
	srand(unsigned(time(0)));

	for(int index=0;index < arraysize;index++)
		num_arr[index] = rand() % 100 + 1;

	print_array(num_arr,arraysize);

	calc_average(num_arr,arraysize,average);

	format();
	cout << "The average = " << average << endl;


return 0;
}

void print_array(int n[], const int s)
{
	for(int i=0;i<s;i++)
		cout << n[i] << " ";
	cout << endl;
}

void calc_average(int n[], const int s, double &av)
{
	double total = 0.0; // local variable

	for(int i=0;i<s;i++)
		total += n[i];

	av = total/s;
}


void format()
{
	cout << setiosflags(ios::fixed | ios::showpoint);
	cout << setprecision(2);
}
Last edited on
Please edit your post and always use code tags - http://www.cplusplus.com/articles/jEywvCM9/

Use the modulus operator.

http://www.cprogramming.com/tutorial/modulus.html
Last edited on
Could you give me an example on how to call the function to use the modulus operator? That is what I'm having problems with.
I cooked this up for you real quick -

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

using namespace std;

void oddOrEven(int arr[], int size, int& sumOfEvens, int& sumOfOdds);

int main(){

	int arr[5] = { 1, 2, 3, 4, 5 };
	int sumOfEvens = 0, sumOfOdds = 0;

	oddOrEven(arr, 5, sumOfEvens, sumOfOdds);

	std::cout << "Sum of evens: " << sumOfEvens << "\nSum of odds: " << sumOfOdds << endl;
	
	return 0;
}

void oddOrEven(int arr[], int size, int& sumOfEvens, int& sumOfOdds){

	for (int i = 0; i < size; i++)
	{
		if (arr[i] % 2 == 0) // if it is even
		{
			sumOfEvens += arr[i]; // add it to the sum of the even numbers
		}
		else
		{
			sumOfOdds += arr[i]; // otherwise, put it in the sum of odd numbers
		}
	}

}
Last edited on
Thank you so much, I understand exactly what I am supposed to do now. Thank you for your help!!
You're very welcome!
Topic archived. No new replies allowed.