Home > Enterprise >  Value returned when printed is different in C (Recursion Problem)
Value returned when printed is different in C (Recursion Problem)

Time:08-31

So I got this question in my end-sem:

//The value returned by sam(3,0) of the below function is:
#include <stdio.h>
int sam(int n,int a)
{

    if(n==0)
         return a;
    else
    {
        a =n;
        sam(--n, a);
        a =n;
    }
}

I calculate using Tree-method and got the answer as 6. But if I compile and directly print return I get 2.

int main()
{
    printf("%ld",sam(3,0));
    return 0;
}

OUTPUT: 2

I checked again and again with what is wrong and couldn't understand. The mystery is if I print(a) just before it returns. It returns 6 (what I calculated).

#include <stdio.h>
int sam(int n,int a)
{
    if(n==0){
        printf("%d",a); //Check the change here
        return a;
    }
    else{
        a =n;
        sam(--n,a);
        a =n;
    }
}

int main()
{
    sam(3,0);
    return 0;
}

OUTPUT: 6

Please help asap, if I explain this I get 4 marks. Enough to change my grade

CodePudding user response:

With a bit of formatting assistance, please note that the below function only explicitly returns when n is 0. Otherwise it performs recursion, but uselessly since it never returns any value created by the recursion.

As a result, you find yourself in the realm of undefined behavior.

#include <stdio.h>

int sam(int n, int a) {
    if (n == 0)
        return a;
    else {
        a  = n;
        sam(--n, a);
        a  = n;
    } 
} 
  • Related