Hey guys, I'm new to this, and am having a lot of trouble figuring out how to correctly use pointers. My question is how to implement them in my code below. I am supposed to use them in the "find_number_odds" function and it should generate how many odd numbers there are. Any help is appreciated! Thank you
Well, you need three things.
1. a variable to store the count - you already have this.
2. a test to determine whether a number is odd or even.
3. a loop to test each of the numbers in the array and increment the count if the number is odd.
It was only a suggestion. It depends on how you look at things.
The function: void print_array(int *n, int size) clearly is using a pointer int *n. What you choose to do with it afterwards is entirely up to you. I just wasn't sure whether you were aware that the two different syntaxes do the same thing. No problem either way as far as I'm concerned.
That would just be using functions, which I don't want to do
- I'm not sure I understand this comment, you have two functions print_array() and find_number_odds() (as well as main()) in your code already. I wasn't suggesting to add any others.
I understand what you mean now. I was confused on what you were trying to say. I thought you meant adding more functions than needed. Here is the code I have, I am extremely new to pointers and don't really know if I'm using them right. I keep getting zero as the number of odds. Please help!
There are a few different problems with this code.
Look first at this (line 7):void print_array(int*,constint);
and next at line 22: print_array(numbers,arraysize);
That code is ok, but I'm using it as an example. line 7, the function is declared. At line 22 the function is called. As I said, no problems there.
However at line 25: void find_number_odds(int*,constint, int*);
that is just another function declaration. You never actually call the function.
There are a couple of other things to look at.
Line 50: odds += num[i];
Remember - as you are already aware - odds is a pointer. The code there is adding to the pointer, so that it will point to something else, some other part of memory. What you need is to add to the value which is pointed to. Dereference the pointer with the * operator.
And one thing I'm not sure of. The code would seem to find the total of all the odd numbers added together. But I thought the program was only meant to count them.
Ah, you are so much help! Like I said, I'm new to all this! I got the function working but it still gives me a weird number, which I believe is what you said, it's adding the odd numbers and telling me the sum. You're right, I need it to just tell me the amount of odd numbers. What would I change in the function?
1 2 3 4 5 6 7 8 9 10 11 12
void find_number_odds(int *num, constint size, int *odds)
{
for (int i = 0; i < size; i++)
{
if (num[i] % 2 == 1)
{
*odds += num[i];
}
}