109k views
4 votes
Write a C++ program with a recursive function that calculates the sum of numbers in an array.

User Webwurst
by
7.4k points

1 Answer

5 votes

Final answer:

To calculate the sum of numbers in an array using a recursive function in C++, define a recursive function that takes the array and the size of the array as parameters. The base case is an empty array, where the sum is 0. Recursively call the function with the array without the first element and add the first element to the sum.

Step-by-step explanation:

To calculate the sum of numbers in an array using a recursive function in C++, you can define a recursive function that takes the array and the size of the array as parameters. The base case of the recursion would be an empty array, where the sum is 0. Otherwise, you can recursively call the function with the array without the first element and add the first element to the sum.

#include

int recursiveSum(int arr[], int size) {
// Base case
if (size == 0) {
return 0;
}
// Recursive case
return arr[0] + recursiveSum(arr + 1, size - 1);
}

int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);

int sum = recursiveSum(arr, size);
std::cout << "Sum of numbers: " << sum << std::endl;

return 0;
}

User Tomasz Janczuk
by
8.4k points