0

Finding the AMOUNT of numbers within an array and a given range using recursion. (C++, arrays, recursion)

Hi! I've been stuck on a recursion assignment for hours now. Basically its recursion practice and I completed everything except one thing: Find the amount of numbers in range within an array. I have to use recursion, and pointers of the array. So far I've done find the sum of array: float sum(const float *pBegin, const float *pEnd){ //Adds all elements in array of float numbers and returns their sum if (pBegin >= pEnd) return 0; return *pBegin + sum(pBegin+1, pEnd); } And check if array has values in range: bool hasValueInRange(float min, float max, const float *pBegin, const float *pEnd){ //Checks if array elements are within min/max range if(pEnd > pBegin && *pBegin <= max && *pBegin >= min){ cout << "Array DOES contain values in range " << endl; return true;} else{ cout << endl << "Array does NOT contain values in range " << endl; return false; } } BUT, now I have to find how many occurences within the range it is. I can't seem to get it to work. Right now I have this: int numberOfValuesInRange(float min, float max, const float *pBegin, const float *pEnd){ if(pBegin >= pEnd) // base case return 0; if (min+max - *pBegin >= min+max) return numberOfValuesInRange(min, max, pBegin, pEnd); } Here is my main function: int main(){ const int size = 5; float sampleArray[5] = {2, 4, 6, 0, 1}; int x = 0; x = numberOfValuesInRange(2,5, &sampleArray[0], &sampleArray[size]); cout << x; return 0; Any help would be lovely, thanks! I know its just one piece of the puzzle missing...

30th Jan 2022, 1:52 PM
Erik Pettersson
Erik Pettersson - avatar
1 Resposta
+ 1
Some points noticed here ... * In main() In call to numberOfValuesInRange, the 4th argument given ( &sampleArray( size ] ) needs some attention, considering valid index were between 0 ~ 4 inclusive, and <size> were 5. * In numberOfValuesInRange() Pointer <pBegin> doesn't seem to be advancing forward (it's not getting incremented).
30th Jan 2022, 2:12 PM
Ipang