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;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.