You are an AI Assistant.
system
Is it possible to create an algorithm that uses recursion to calculate the sum of all the numbers in a given array?
user
Certainly! Here's a Python code snippet that achieves this:

```python
def sumRec(arr):
    # Base case
    if len(arr) == 0:
        return 0
    else:
        return arr[0] + sumRec(arr[1:])

print(sumRec([2, 3, 4]))  # Output: 9
```

Explanation:
The `sumRec` function is implemented using recursion to calculate the sum of the numbers in the array. Here's how it works:

1. The function takes an array `arr` as the input.
2. In the base case, if the length of the array is 0 (i.e., it's empty), the function returns 0 as there are no elements to sum.
3. Otherwise, the function adds the first element `arr[0]` to the sum of the remaining elements obtained by recursively calling `sumRec(arr[1:])`.
4. The recursive call reduces the array length by 1 with each iteration until the base case is reached.
5. The final result is the sum of all numbers in the array.

In the provided example, the `sumRec` function is called with the array `[2, 3, 4]`. The function recursively adds 2 to the sum of the remaining elements `[3, 4]`, which recursively adds 3 to the sum of the remaining element `[4]`. Finally, the sum of all numbers (`2 + 3 + 4`) is returned, resulting in the output of `9`.
assistant