0

I just found out about recursive functions about a few minutes back. I was playing around with them and now I am getting different outputs from the following functions:

int function(int m)   {
    m = 2*m;
    std::cout<<"In f m = "<<m<<std::endl;
    if(m > 20)
    {
        return m;
    }
    function(m);
};

int function2(int n)   {
    n = 2*n;
    std::cout<<"In f2 n = "<<n<<std::endl;
    if(n < 20)
    {
        function2(n);
    }
    return n;
};

int main()  {
    int a = 2;
    std::cout <<"function(a) = "<<function(a)<<std::endl;
    std::cout <<"function2(a) = "<<function2(a);
    return 1;
}

To this I get the output:

In f m = 4
In f m = 8
In f m = 16
In f m = 32
function(a) = 32
In f2 n = 4
In f2 n = 8
In f2 n = 16
In f2 n = 32
function2(a) = 4

Shouldn't they both yield result of 32?

2
  • 1
    Your first function is actually exhibiting undefined behavior because it is not returning a value if the base case isn't triggered. Commented Jun 30, 2013 at 7:46
  • @CharlesSalvia What do u mean by 'base case' here? Commented Jun 30, 2013 at 8:02

2 Answers 2

3

Because you only do return n and don't assign it from the recursive calls, so it will for the first call always be 4.

You should to e.g.

if(n < 20)
    n = function2(n);
return n;
Sign up to request clarification or add additional context in comments.

2 Comments

That fixed it! Don't know why I didn't notice that.
I should have noticed that n is local to every function call.
0

Actually in function2,whether n less than or greater than 20 or not,statement return n will always be executed as the if statement will not return.so when you pass the argument a=2 in function2, it will return 4.If u want both of them to return the same result. u can modify function2 like

if(n < 20)
{
    function2(n);
}
else
    return n;

Comments

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.