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

I can not get the cumulative sum to work properly. It is suppose to add, lets sa

ID: 3569350 • Letter: I

Question

I can not get the cumulative sum to work properly. It is suppose to add, lets say for 5, 1+2+3+4+5 but it is giving me some crazy high number.

#include <iostream>
using namespace std;

long long int cumulativeSum(int num)
{
   if(num!= 0)
       return num + cumulativeSum(num-1);
}


int main()
{
   long long int value;

   value = cumulativeSum(20);
   cout << "The cumulative sum of 20 is: " << value << endl;

   value = cumulativeSum(5);
   cout << "The cumulative sum of 5 is: " << value << endl;

   value = cumulativeSum(100);
   cout << "The cumulative sum of 100 is: " << value << endl;

   system("pause");
}

Explanation / Answer

//You were missing out the base case to which is required to terminate the recursion with a suitable value

#include <iostream>
using namespace std;

long long int cumulativeSum(int num)
{
if(num!= 0)
return num + cumulativeSum(num-1);
else return 0;//Base case is required to terminate recursion
}


int main()
{
long long int value;

value = cumulativeSum(20);
cout << "The cumulative sum of 20 is: " << value << endl;

value = cumulativeSum(5);
cout << "The cumulative sum of 5 is: " << value << endl;

value = cumulativeSum(100);
cout << "The cumulative sum of 100 is: " << value << endl;

}

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