Can anyone explain how to do the calculation I have below using recursion??
1 2 3 4 5 6
int RecursiveEvenSum (int num, int &finalRecursiveSum)
{
// will compute and return the same sum using recursion
for (int i = 0; i <= num; i += 2)
finalRecursiveSum += i;
}
Should be calculating the sum of all EVEN integers from 1 to num (inclusive)
As I showed in other thread the function can look the following way
1 2 3 4
int LoopEvenSum ( int num )
{
return ( ( num > 1 ) ? 2 + LoopEvenSum ( num - 2 ) : 0 );
}
another way is
1 2 3 4 5 6 7 8 9 10 11 12 13 14
void RecursiveEvenSum (int num, int &finalRecursiveSum)
{
// will compute and return the same sum using recursion.
if (num < 2)
{
finalRecursiveSum = 0;
}
else
{
RecursiveEvenSum (num - 2, finalRecursiveSum);
finalRecursiveSum += 2 * ( num / 2 ) ;
}
}
Recursion means to have the function keep calling itself until some condition is met. So instead of having a for loop, you would call RecursiveEvenSum again.
You'll probably need to change/overload the function so that it takes 3 arguments.