简体   繁体   中英

Compute the sum recursively by dividing array

I'm trying to create a function to compute the sum of elements in the array recursively. I wanted to try the approach of halving the array every iteration.

Here's what I have so far.

int sumRec(int *A, int n, int start, int end)
{
     if (start == end){
         return A[end];
     }
     mid = n/2;
     return sumRec(A, n, start, mid) + sumRec(A, n, start, mid + 1);
}

Am I on the right track? Thanks.

You don't need to pass n to the function.That's not needed. Currently your program will run into an infinite recursion.

You can use

mid = (start+end)/2;

There are many more errors in your code.

Here's a similar code that could do the job

int sumRec(int *A, int start, int end)
{
     if (start <= end)
     {
        int mid = (start+end)/2;
        return A[mid] + sumRec(A,start, mid-1) + sumRec(A,mid+1,end);
     }
     return 0;
}

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