Design a recursive function to solve the following problem: sum up a given array a[0]..a[m-1] & return the sum to the caller
时间: 2024-02-15 20:03:21 浏览: 22
Here's an example of a recursive function that sums up an array:
```
int array_sum(int a[], int m) {
// Base case: if the array has only one element, return it
if (m == 1) {
return a[0];
}
// Recursive case: split the array in half and recursively sum up each half
int mid = m / 2;
int left_sum = array_sum(a, mid);
int right_sum = array_sum(a + mid, m - mid);
// Return the sum of the left and right halves
return left_sum + right_sum;
}
```
This function takes an array `a` and the number of elements `m` as parameters. It uses recursion to divide the array in half until each sub-array has only one element. At that point, it returns the value of the single element. The function then adds up the values returned by the left and right sub-arrays and returns the sum to the caller.