#include<iostream>
usingnamespace std;
int add(int);
int main() {
int n, sum;
cout <<"Enter a no\n";
cin >> n;
sum = add(n);
cout<<"Addition of first "<<n <<" numbers is"<<sum;
return 0;
}
int add(int x){
int S=0;
if(x!=0) {
S= x+add(x-1);cout <<"S="<<S<<"\n";
}
return S;
}
In above add() , int S=0;
Is S being assigned 0 at every recursive call . OR only once.
S is defined within the scope of the recursive function, thus each call of add will have its own S, initialized to 0. Else, it wouldn't work.
You can do it with a single S too, if you declare it outside the function scope. You'll have to change the function add() to, for example, simply adding x to S and then calling add(x-1) (it becomes a void function if you do it that way).
Protip: using the steps above is, in some cases, an easy way to transform a recursive function into a simple loop, which is (often? usually? always?) better in terms of performance.