Click here to Skip to main content
15,920,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to make a function that calculates the average and return the number of values larger than the average. For example, passing an array of {4, 5, 12, 17} should return 2 (because 12 and 17 are larger than the average 9.5). So far I wrote the function to return the average, but how can I make it count the numbers larger than the average and keep it tail-recursive?
Below is the average function.

What I have tried:

C++
int TAvg(int* a, int size, int acc=0, int num=0){ //acc is the sum so far, num is the number of all elements
if (size == 0){ 
    return (acc / num); 
}
return TAvg(a, size - 1, acc+a[size-1], num+1);}
Posted
Updated 15-Nov-16 5:35am
Comments
Nelek 15-Nov-16 10:09am    
Must you do it all in the very same function?

It sounds like homework...

To do:
1. calculate the average recursive.
2. by unwinding the recursion count the above average.
 
Share this answer
 
We do not do your HomeWork.
HomeWork is not set to test your skills at begging other people to do your work, it is set to help your teacher to check your understanding of the courses you have taken and also the problems you have at applying them.
Any failure of you will help your teacher spot your weaknesses and set remedial actions.
So, give it a try, reread your lessons and start working. If you are stuck on a specific problem, show your code and explain this exact problem, we might help.

Unless you are studying recursion, I recommend to not use it for this kind of function. Because recursion do not make the writing simpler, the compiler is likely to rewrite as a loop, and if not, it is a kind of system abuse.
Quote:
but how can I make it count the numbers larger than the average and keep it tail-recursive?
Short answer, you can't. Simply because you need the average before starting to count.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900