patterncppMinor
Simple recursive Summing program
Viewed 0 times
summingrecursivesimpleprogram
Problem
Any tips on how to improve this simple recursion program?
#include
#include
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);
}
}Solution
I think I'd prefer something like this:
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.
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.
Code Snippets
int findsum(int const *list, int length) {
if (0 == length)
return 0;
return list[0] + findsum(list+1, length-1);
}Context
StackExchange Code Review Q#5314, answer score: 6
Revisions (0)
No revisions yet.