recurtion Helppppppppppppppppppppppppppppppppppppppp

Why My Sum Value Didnt Update???
its still show me the first one....!!!!!!!!

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
29
#include<iostream>>

using namespace 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);

}
Line 13: You make a recursive call to series(), but you're ignoring the return result.

How are you going to get the result of the recursive call if you ignore the result?
You probably meant it to be tail recursive. If so you need to pass sum as an accumulating parameter:

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
29
30
31
32
33
34
35
36
37
38
39
40
41
#include<iostream>

using namespace 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);

}
Last edited on
Topic archived. No new replies allowed.