Jake
Jake

Reputation: 7

C++ Recursive functions

I'm learning C++ and I have trouble with getting recursion working when a function is called by itself.

#include <iostream>

using namespace std;

int countdown(int y) {
    if (y==1) {
        return 1 && cout << y << endl;
    }
    else {
        return countdown(y-1);
    }
}

int main () {
    cout << "Countdown from ten: " << endl;
    cout << countdown(10) << endl;
}

Of course there are other ways to achieve this, but really I created this example to verify my own understanding of how functions are called recursively.

In the example I added && cout << y to verify if y is being passed to the function as 1, which always appears to be the case irrespective that I call the function as countdown(10).

Could someone tell me if I'm missing something obvious here please?

Upvotes: 0

Views: 9855

Answers (2)

Christopher Creutzig
Christopher Creutzig

Reputation: 8774

Your call stack looks like this:

main
  countdown(10)
    countdown(9)
      countdown(8)
        countdown(7)
          countdown(6)
            countdown(5)
              countdown(4)
                countdown(3)
                  countdown(2)
                    countdown(1)
                      std::cout << 1 << std::endl;

If you want to see the whole countdown, move the output command in front of the if condition.

Also, your style of writing the output is very unidiomatic. Note that it only works because 1 %&& cout converts the cout to bool and bool can be converted to int. Please don't write code like that.

Upvotes: 1

Steve Fallows
Steve Fallows

Reputation: 6424

Your ' cout << y ' only executes if y has been tested to be one.

This version does what I think you want:

#include <iostream>
using namespace std;

int countdown(int y) 
{
    cout << y << endl;
    if (y==1)
    {
        return 1;
    }
    else 
    {
        return countdown(y-1);
    }
}

int main() 
{
    cout << "Countdown from ten: " << endl;

    cout << countdown(10) << endl;
}

Upvotes: 3

Related Questions