In this program, the main function will take the size of the array as input and create a dynamic array of that size. Users will enter the values of the array. Please complete the definition of findSum function which will use recursion to calculate the sum of the values of the number in the array.
#include<iostream>
usingnamespace std;
int findSum(int a[], int size);
int main()
{
int n;
cout << "Please enter the size of the array: ";
cin >> n;
int *array = newint[n];
cout << "Please enter the values of the array: " << endl;
for(int i=0; i < n ;i++)
{
cin >> array[i];
}
cout << "The sum of the values in the array is " << findSum(array, n) << endl;
return 0;
}
your question is unclear, though you did post code.
It just looks like a school question, not what you specifically are stuck on, and it looks like school provided startup code, not something you tried and are struggling with.
how would you stop the recursion? Perhaps, if size passed in were zero?
something like return a[size-1]+findsum(a,size-1) unless its zero, then you just stop and return the value so far... its going to be 2-3 lines of code to do that.
Summing the elements of an array by recursion, as the topic title mentions, really is "there be dragons here" territory. Yes, it can be done, but iterating through the array within the confines of the function is a less cumbersome way of doing it. Using a for loop, for example.
#include<iostream>
usingnamespace std;
int sos(int n)
{
if (n==1)
return 1;
elsereturn n+sos(n-1);
}
int main()
{
int findSum(int *a, int size);
int n;
cout << "Please enter the size of the array: ";
cin >> n;
int* A= newint[n];
cout << "Please enter the values of the array: " << endl;
for (int i = 0; i < n;i++)
{
cin >> A[i];
}
cout << "The sum of the values in the array is " << findSum(A, n) << endl;
return 0;
}
#include <iostream>
// Return sum of elements in A[0..N-1]
// using recursion.
int findSum(int A[], int N)
{
if ( N <= 0 ) { return 0; }
return (findSum(A, N - 1) + A[ N - 1 ]);
}
int main()
{
int A[] { 1, 2, 3, 4, 5 };
int N { sizeof(A) / sizeof(A[ 0 ]) };
std::cout << "The sum is " << findSum(A, N) << '\n';
}
@George P, why do you say it’s “easier” to go backwards through the array? In the OP it’s a pointer to the beginning of a dynamic array: just increment it by 1 each recursion.
#include <iostream>
int findSum(int a[], size_t size) {
return size ? *a + findSum(a + 1, size - 1) : 0;
}
int main() {
size_t n {};
std::cout << "Please enter the size of the array: ";
std::cin >> n;
constauto A { newint[n] };
std::cout << "Please enter the values of the array: ";
for (size_t i {}; i < n; ++i)
std::cin >> A[i];
std::cout << "The sum of the values in the array is " << findSum(A, n) << '\n';
delete[] A;
}
PS. Where did function sos() come from when the given function declaration is for findSum() ?