\$\begingroup\$
\$\endgroup\$
2
Any tips on how to improve this simple recursion program?
#include <iostream>
#include <cstdlib>
using namespace std;
int findSum(int*, const int, int, int);
int main()
{
int length = 5, sum = 0, n = 0;
int list[length];
for (n; n < length ; n++ )
{
list[n] = n + 1; //initializes array elements to 1,2,3,4,5
}
n = 0;
cout << findSum(list, length, n, sum) << endl;
system("pause");
return 0;
}
int findSum(int list[], const int length, int n, int sum)
{
if (n == length) //if end of list has been reached, stop recursion
{
return sum;
}
else
{
sum += list[n]; //adds list elements
n++; //increments list
return findSum(list, length, n, sum);
}
}
rolfl
98.1k17 gold badges219 silver badges419 bronze badges
-
\$\begingroup\$ Do you want to improve the recursion or do you want a better technique? \$\endgroup\$Loki Astari– Loki Astari2011年10月11日 23:04:56 +00:00Commented Oct 11, 2011 at 23:04
-
\$\begingroup\$ Recursion must be used. \$\endgroup\$mwmnj– mwmnj2011年10月12日 00:30:13 +00:00Commented Oct 12, 2011 at 0:30
1 Answer 1
\$\begingroup\$
\$\endgroup\$
0
I think I'd prefer something like this:
int findsum(int const *list, int length) {
if (0 == length)
return 0;
return list[0] + findsum(list+1, length-1);
}
This follows one of the typical recursive formulations -- basically a function that's almost like an inductive proof. Start by establishing a correct value for the simplest possible base case (or some obvious base case anyway), and then establish a pattern that's correct for some some sort of "Base+1" type of case.
answered Oct 11, 2011 at 22:36
lang-cpp