Doubt: Recursive functions

The below is a program using recursive function to find sum of
first n numbers .

The program works correctly .
But I have one doubt .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream>

using namespace 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.

Thankyou for your time.
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.
I understand now , and thanks for the tip too .
Topic archived. No new replies allowed.