newbie
newbie

Reputation: 25

How to return a current function value in a recursive function call

int countdown(int num) 
{
    if (num ==1)
    {
        return 1;}
    else 
    {
        return num + countdown(num-1);}
}

I want to know the current value of the function each step .How can i print out the value of countdown function each time num decrease ? Thanks

Upvotes: 1

Views: 149

Answers (2)

Raju Ahmed
Raju Ahmed

Reputation: 354

This can do it-

int countDown(int num){
    cout<<num<<endl;
    if(num==1)
        return 1;
    else{
        int r= countDown(num-1);
        cout<<"Countdown: "<<r<<endl;
        return num + r;
    }
}

each time it recursively calls the countDown function, the first cout will show you the value of num variable and second cout will show you the value of your recursive function after decrement each time.

Upvotes: 1

dj1986
dj1986

Reputation: 362

If I understand correctly, you want the value returned by countDown(num-1) each time. You can try this.

int countdown(int num) 
{
    if (num ==1)
    {
        return 1;}
    else 
    {
        int temp = countDown(num-1); 
        count<< temp<<endl; 
        return num+temp;
}

Let me know if this worked for you.

Upvotes: 1

Related Questions