4
\$\begingroup\$

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
asked Oct 11, 2011 at 22:23
\$\endgroup\$
2
  • \$\begingroup\$ Do you want to improve the recursion or do you want a better technique? \$\endgroup\$ Commented Oct 11, 2011 at 23:04
  • \$\begingroup\$ Recursion must be used. \$\endgroup\$ Commented Oct 12, 2011 at 0:30

1 Answer 1

6
\$\begingroup\$

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
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.