I have a query regarding a recursive function. This is my program.
#include <stdio.h>
int fun(int);
int main(void)
{
int x;
int k=3;
x = fun(k);
printf("%d\n",x);
return 0;
}
int fun(int a)
{
int f;
if(a == 1) return (1);
f = 2 + fun(a-1);
return (f);
}
where I have a value K=3
in STEP-6
. In STEP-7
the function fun(k)
pass the value of K to the called function in STEP-11
int fun(int a)
. In called function fun(int a)
recursion occurred 2 times that is (3,2) making the value of a=1
. Which is later in STEP-14
, the value of f
becomes 3, because f = 2 + (fun(1)=1). In STEP-16
it get return to called function i.e fun(int a)=3
. Which is supposed to print the value of x is 3
, unlikely it is not. It is x =5
Let's check the calling sequence of fun()
, shall we?
With an argument value of 3
, starting from main()
x = fun(3)
f = 2 + fun(2);
f = 2 + fun(1);
Now, let's check the return values, just in the reverse order.
fun(1)
returns 1
, fun(2)
, returns 2 + 1
or 3
, fun(3)
returns 2 + 3
or 5
and that is the call made from main()
. So, in main()
, x
gets a value of 5
.
The evalution of fun(3)
looks like this:
fun(3)
2 + fun(3-1)
2 + fun(2)
2 + 2 + fun(2-1)
2 + 2 + fun(1)
2 + 2 + 1
5
From your description, I think you have some misconceptions about scopes in C (and recursion in general). The fact that f
is assigned the value 3
inside fun(2)
does not mean that the value of f
in the scope of fun(3)
changes - they are entirely separate variables.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With