#include<iostream>>
usingnamespace std;
class test{
public:
int series(int n){
int sum=0;
if(n==0) return 0;
else{
sum=sum+n;
series(n-1);
cout<<n<<" + ";
}
return sum;
}
};
int main(){
test p;
int n;
cout<<"Enter N ";
cin>>n;
cout<<endl<<"Sum Is "<<p.series(n);
}
#include<iostream>
usingnamespace std;
class test
{
public:
//sum accumulates the previous sums and is passed to the next recursive level
int series(int n, int sum)
{
//the cout statements show you that upward propagation does not happen.
cout << "n: " << n << ' '
<< "sum: " << sum << endl;
//the function is returned at the last recursive level,
//so you don't propagate upward. Hence it is called tail recursive.
if(n==0) return sum;
else
{
sum = sum + n;
series(n-1, sum);
}
}
};
int main()
{
test p;
int n;
int sum = 0;
cout << "Enter n: ";
cin >> n;
cout << endl << "Sum is " << p.series(n, sum);
}