Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Trying to figure out why int recursiveSum(int n) won\'t work correctly. What sho

ID: 3850696 • Letter: T

Question

Trying to figure out why int recursiveSum(int n) won't work correctly. What should i write for the recursive function call(else)?


#include <iostream>
using namespace std;

int recursiveSum(int n);
int main()
{
int n; cout << "Enter a number to calculate the sum: ";
cin >> n;

cout << "The sum from 1 to " << n << " is " << recursiveSum(n) << endl;
return 0;
}

int recursiveSum(int n)
{
int sum;

if (n = 1) // base case
{
return n;
}
else // recursive function call
{
return ???;
}

return sum;
}

Explanation / Answer

#include <iostream>

using namespace std;

int recursiveSum(int n,int sum);

int main()

{

int n; cout << "Enter a number to calculate the sum: ";

cin >> n;

int sum=0; //sum should be declared in outer scope or else global variable.

cout << "The sum from 1 to " << n << " is " << recursiveSum(n,sum) << endl;

return 0;

}

int recursiveSum(int n,int s)

{

if (n == 1) // base case

{

return s+n;

}

else // recursive function call

{

s=s+n;

return recursiveSum(n-1,s);

}

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote