15,920,438 members
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
Nelek 15-Nov-16 10:09am
Must you do it all in the very same function?

## Solution 1

It sounds like homework...

To do:
1. calculate the average recursive.
2. by unwinding the recursion count the above average.

## Solution 2

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.
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.