Question

i would like to ask about the array recursion in C, Let say i have an array in float

 float arr[] = {12.5, 5.5, 6.0, 18.0};

i want to count the number which is greater than 10, so the result should be 2. However, below is what i did

int cntArray(float arr[], int size) 
{
    int number = 0;
    if((cntArray(&arr[1], size - 1))>=5)
        number++;

    return number;
}

int main() 
{
    float arr[] = {12.5, 5.5, 6.0, 18.0};
    int result;

    result = cntArray(arr, 4);

    printf("The result is : %d", result);
}

But it returns 0 as result, any solutions for it? Thanks

Was it helpful?

Solution 5

int cntArray(float arr[], int size) {
    int number = 0;
    if (size > 0) number = cntArray(&arr[1], size - 1);
    if (arr[0] > 10) number += 1;
    return number;
}

OTHER TIPS

Another example:

int cntArray(float arr[], int size) {
        if (!size) return 0;

        return (arr[0] > 10.0 ? 1 : 0) + cntArray(&arr[1], size - 1);
}

Edit #1 (in reply to comment):

This simply evaluate through a ternary operator (?:) if the first index of arr[] is greater than 10.0. If true, 1 will be the lvalue, otherwise will be 0. The lvalue of cntArray(&arr[1], size - 1) (which will process the next element on the array after decrementing size and if size is different than 0, which in this case will immediately return 0) will be added to the lvalue of the ternary operator. Applying this recurring logic, the aftermath will be the number of elements in the array that are greater than 10.0.

Your cntArray() function lacks a recursion base case, and also seems to hardcode the wrong value (5 instead of 10).

It should be something like:

int cntArray(const float *arr, size_t size)
{
  if(size > 0)
  {
    /* Count the first element, then recurse. */
    const int count = arr[0] >= 10.f;
    return count + cntArray(arr + 1, size -1);
  }
  return 0;
}

Your logic is severely flawed: You don't actually check if a value in the array is larger than 10. you also always return number which will always be zero meaning the condition will always be false.

int cntArray(float arr[], int size){
    int number = 0;
    if((number = cntArray(&arr[1], size - 1))>=5)
        number++;
    return number;
}

You maybe want to change 5 to 10.

I'm not sure what does this portion of your code does.

if((cntArray(&arr[1], size - 1))>=5)
   number++;

I would something like this instead:

int cntArray(float arr[], int index, int size){
    if (index == size) return 0;  // base case

    int rest = cntArray(arr, index + 1, size);  // how many elements are greater
                                                // then 10 in rest of the array
    if (arr[index] > 10)
        return rest + 1;
    else
        return rest;
}

And call it in the main like this:

cntArray(arr, 0, 4);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top