You might want to initialize your counter array.
John A
Vampirical Lurker
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
>Why is this?
Because you misplaced your return statement.
int count_array(int sample_array[], int counter[], int number_used)
{
for(int index=0; index<number_used; index++)
{
for(int index2=0; index2<number_used; index2++)
{
if (sample_array[index]==sample_array[index2])
counter[index]++;
}
return counter[index]; // drop this down below the }
}
}
Why are you even using a return statement at all? It's not like the last element in the array is going to be very useful without the other values...
And by the way you may want to consider using a debugger, they make errors like these really easy to spot.
John A
Vampirical Lurker
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
RaCheer. please consider formatting your code better. You really need to indent so the code can be followed.
WaltP
Posting Sage w/ dash of thyme
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
int counter[100] = {0};
>> Just curious, is it guaranteed that this will always initialize elements indexed 1 to 99 with 0 ?
IMHO...it would be easier just to do it the way you're already doing...get the list filled, then sort it...think of it this way, you spend the time to get one list filled then call one function to sort the list...the other way, you would have to call the function to sort the list every time you added to it...it's simply not as efficient...
I hope no one intended to say that to "keep the list sorted after every insert" you have to "call sort function after every insert". :eek:. One can always find out the "right slot" where a new element should be inserted before inserting it. Where right slot is the slot that will ensure list's sorting sequence doesn't change. (e.g. lower/upper_bound() functions)
Now even if we do it the right way, from efficiency point of view I won't fully agree. If the array is large enough it might be faster to insert in a sorted order, than insert all and then sort.
But then you really won't be thinking of using a simple single dimensional array, but some kinda complicated tree structure (or a linked list perhaps as a second choice).
thekashyap
Practically a Posting Shark
811 posts since Feb 2007
Reputation Points: 254
Solved Threads: 75
And BTW, no one seems to have spoken abt count() and count_if()..
You can use them as well..
thekashyap
Practically a Posting Shark
811 posts since Feb 2007
Reputation Points: 254
Solved Threads: 75