简体   繁体   中英

Finding the maximum of an array recursively

I am learning recursion. As an exercise I am trying to find the maximum of an array recursively.

int recursive (int *arr, int n, int largest) {
  if(n==0)
    return largest;
  else {
    if (*(arr+n)>largest) {
      largest = *(arr+n);
      recursive(arr, n-1, largest);
    }
  }
}

int main() {
  int length = n-1;
  int largest = v[0];
  int z = recursive(arr, length, largest);

  printf("\n%d", z);
}

I followed your suggestions, using pointers instead of arrays, and probably the program looks way better. But still it is not doing it's not showing the maximum correctly. I think the logic is correct.

In C usually you can't declare an array whose size is unknown at compile-time, hence int v[n] is dangerous code.
Depending on your compiler and the compiler's settings this could be a compile error or it could be a bug.

For such problems you need to learn about pointers and dynamic memory allocation .

Side-note: After C99 there are stuff like Variable Length Arrays but the rules are a little advanced.

Also to pass an array to a function you give the array a pointer as an argument:

int z = recursion(v, n, v[0]);

instead of:

int z = recursion(v[n], n, v[0]);

First thing pay attention to compiler warnings, your recursive function doesn't return value when you enter the else part.

Now the second thing is please don't use things like *(arr+n) which is hard to read instead use arr[n], also while just a preference when using arrays as function arguments use int arr[] to call the function instead of int *arr (in the first version it's clear you should pass an array).

Third thing is to name your things instead of int recursive describe what the function is doing for example int maxElemRecursive

So your recursive function should be something like

int maxElemRecursive(int arr[],int n,int largest)
{
    if(n==0) return largest;
    if(arr[n] > largest) // No need for else because return largest; would've returned value;
    {
        largest = arr[n]; 
    }
    return maxElemRecursive(arr,n-1,largest); // You have to return the value of the function.
                                             // You still pass the array with just arr.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM