adding odds

hi everyone,
so I want SumOdds to add for example the first 4 odds, but the function is taking 4 as an index so it will start at the beginning of the array and sum whatever odds are in the first 4 positions.

ideas please?

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
61
62
63
64
65
66
67
 

#include <iostream>
#include <iomanip>
#include <cctype>

using namespace std;

/*Given Function prototypes*/
void PrintArray(const int arr[], const int size);
void FillArray(int arr[], const int size);

int SumOdds(int arr[], const int SIZE, int odds);

int main()
{
	const int SIZE = 15;
	int arr[SIZE];
	int oddsvalue;


	FillArray(arr, SIZE);

	PrintArray(arr, SIZE);

	cout << "\nHow many odd numbers to add: ";
	cin >> oddsvalue;
	cout << "\nThe sum of the first " << oddsvalue << " odd numbers is: ";
	cout << SumOdds(arr, SIZE, oddsvalue) << "\n";

	return 0;
}

int SumOdds(int arr[], const int SIZE, int oddsvalue)
{
	int sum_odds = 0;
	for (int i = 0; i < oddsvalue; i++)
	{
		if (arr[i] % 2 != 0)
			sum_odds += arr[i];
	}

	return sum_odds;
}


void PrintArray(const int arr[], const int size)
// this function prints the contents of the array
{
	cout << "\nThe array:\n { ";
	for (int i = 0; i < size - 1; i++)	// print all but last item
		cout << arr[i] << ", ";

	cout << arr[size - 1] << " }\n";	// print last item
}

void FillArray(int arr[], const int size)
// this function loads the contents of the array with user-entered values
{
	cout << "Please enter " << size
		<< " integers to load into the array\n> ";

	for (int i = 0; i < size; i++)
		cin >> arr[i];			// enter data into array slot
}

You need to loop through the array like normal, and have a second number to keep track of how many odds you've found. break from the loop when you've found enough.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int SumOdds ( int arr[], const int SIZE, int oddsvalue )
{
	int sum_odds = 0, num_odds = 0;

	for ( int i = 0; i < SIZE; ++i )
	{
		if ( arr[i] % 2 )
		{
			sum_odds += arr[i];

			++num_odds;

			if ( num_odds > oddsvalue - 1 )
				break;
		}
	}

	return sum_odds;
}
Last edited on
thank you Yay295, you're a lifesaver!

How would I check if the user inputs say 10 and there are no 10 odds in the array?
I would make a second function that just returns the number of odds in an array. Don't try to make one function do too much.
got it! thanks again!
Topic archived. No new replies allowed.