for my understanding i write some code in that i just change increment in diffrent place but it differs the answer in recursion

Viewed 46

why the answer is diffrent for these codes

#include<stdio.h>
void recursion(int a,int temp)
{
if(temp==0)
{
    printf("%d ",a);
   return;
}
else
{
    a++;
    recursion(a,temp-1);
    printf("%d ",a);
}
}
int main()
{
int a=5,temp;
temp=a;
recursion(a,temp);
}

output:10 10 9 8 7 6

#include<stdio.h>
void recursion(int a,int temp)
{
if(temp==0)
{
    printf("%d ",a);
   return;
}
else
{

    recursion(a+1,temp-1);
    printf("%d ",a);
}
}
int main()
{
int a=5,temp;
temp=a;
recursion(a,temp);
}

output:10 9 8 7 6 5

3 Answers

Because a++ is changing a, but a + 1 is not. So when you do printf("%d ",a); the new incremented a is printed.

    // let say "a" were 5 when execution reached here
    a++; // now "a" is 6
    recursion(a,temp-1); // passing 6
    printf("%d ",a); // printing 6

While with the other version

    // let say "a" were 5 when execution reached here
    recursion(a+1,temp-1); // passing 5 + 1 = 6
    printf("%d ",a); // printig 5 since "a" has not changed

In first code 'a++' is used which increases the value of 'a' which is also used in next print statement.

But in another code 'a+1' is used in recursion so value of 'a' is not increased for print statement.

** Also one note .. this seems like an assignment ... please start thinking in step by step way to understand your own code better

in second one ,you are sending a+1 to function.

In recursive function when you send a+1 as int a argument of function ,it will count as a but when it returns , a+1 will be returned and you will print a.

a++ will increase a but a+1 won't change a.

this is reason for different results.

Related