Easy, Small Question

Hey guys, I'm about done with this project. I am supposed to use pointers to tell me exactly how many odd numbers are in an array. Everything works correctly, except it doesn't tell me the number of odds, it just adds them. What would I change in the function to make it just count the amount of odds in the array?

Thank you!


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
  #include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;

void print_array(int*,const int);
void find_number_odds(int*,const int, int*);

int main()
{
    srand(unsigned(time(0))); // seed the random number generator

    const int arraysize = 100;
	int numbers[arraysize] = {11,12,14,15,18}, *numbersPtr, numodds = 0, *oddPtr;
    numbersPtr = numbers;
    oddPtr = &numodds;

    for(int i = 0;i<arraysize;i++)
        *(numbersPtr + i) = rand() % 100 + 1; 
    
    print_array(numbers,arraysize);

    cout << endl;

	
    
	find_number_odds(numbers, arraysize, &numodds);
	// function call



    cout << "The number of odds in the array = " << *oddPtr << endl;
}

void print_array(int *n, int size)
{
      int lines = 0;
      for(int index = 0;index < size; index++)
	  {
          cout << setw(6) << *(n + index) << " ";
          lines += 6;
            if( lines % 66 == 0)
                cout << endl;
	  }
}

void find_number_odds(int *num, const int size, int *odds) 

// This is where I'm having problems, I need it to count the number of odds, not sum them.
{
   
	for (int i = 0; i < size; i++)
	{
		if (num[i] % 2 == 1)
		{
		*odds += num[i];
		}

	}
}
Beware that I have only glansed through this program.

*odds += num[i];
As you suspect, what you're doing here is adding them. But what you want to do is simply count them, so you can just add the number 1 each time you find an odd yes?

1
2
3
4
if (num[i] % 2 == 1)
{
    *odds += 1;
}


This way it works like a counter.
Last edited on
Ah, that's it! It works perfectly now, I'm relatively new to programming! Thanks for your help :)
Topic archived. No new replies allowed.