0

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?

0

2 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I see what I was doing wrong - cout << y should have been inside the function. Thanks for your help.
1

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.

2 Comments

Hi Christopher, thanks for the advice. Was that in reference to the return 1 && cout << y << endl; line? Was there a better way to troubleshoot why this wasn't working?
Yes. Put the cout in a line of its own, in front of the return command. The && operator is not useful in all the places a textual description would say “and,” it has a very specific meaning, which you did not mean here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.