I am trying to find the output for fun(5). But I am getting an unexpected result (19) and don't know why.
My doubt is for n =5 for instance, it would return fun(3) + 3. After that would the return fun(4) + x work or the function fun will be called again?
int fun(int n)
{
static int x = 0;
if (n<=0) return 1;
if (n>3)
{
x = n;
return fun(n-2) + 3;
}
return fun(n-1) + x;
}
This is the sequence of what happens:
call fun(5)
x=0; which, being the initialisation of a static local variable,
only happens before the very first call to fun()
5>3: x=5 (not a problem, static vars can be changed and keep the value)
return fun(3)+3
return fun(2) + 5
return fun(1) + 5
return fun(0) + 5
return 1
return 1 + 5
return 6 + 5
return 11 + 5
return 16 + 3
The exact meaning an relation of the following lines seem to be of interest to you.
static int x = 0;
/* Defines a local but static variable, initialised to 0;
the initialisation happens before the first execution of the function,
conceptually at the beginning of the whole program (credits John Bollinger).
This does NOT cause an assignment to 0 during each execution of the function.
The static attribute also means that the value at the end of one
execution will still be found in the variable at the start of the next
execution, even and especially if that start is before the end of the current execution,
which is typical for recursive functions.
*/
/* ... */
x = n;
/* This conditional (inside an if) assignment in the middle of the
recursive function changes the value of the static variable away from
the initialisation value, to e.g. 5.
If/because no other assignment occurs, the value will stay in the
for the rest of the program.
*/
Related
First take a look:
#include <stdio.h>
static int v1 = 0;
int fun()
{
static int v2 = 0;
++v2 && ++v1;
printf("%i\n", v2);
return v2;
}
int main()
{
++v1;
printf("%i\n", fun());
printf("%i\n", v1);
}
OUTPUT:
1
1
2
So the whole thing is about global static & local static variables in C, so the main property of the static variable is the fact that it's "Preserving it's value", but here it doesn't, the first piece of output is as expected : the value of v2 in fun() should ++v2 which is 1 but the second piece is not, what expected is when it called by main() it's preserved value would be 1 and it would again ++v2 so the second output expected to be 2 .
When we eliminate return v2 the program works as expected.
#include <stdio.h>
static int v1 = 0;
int fun()
{
static int v2 = 0;
++v2 && ++v1;
printf("%i\n", v2);
}
int main()
{
++v1;
printf("%i\n", fun());
printf("%i\n", v1);
}
OUTPUT:
1
2
2
The question is Why ? thanks.
main() increments v1, so its value is 1.
When you call fun(), it increments v2 and v1, so v2 is 1 and v1 is 2.
Then it prints v2, so it prints 1. This is the first line of output.
Then it returns v2, so it returns 1.
Then main() prints the return value, so it prints 1. This is the second line of output.
Then main() prints v1, so it prints 2. This is the third line of output.
You don't call fun() twice, so nothing in your snippet depends on whether the value is preserved. In order to see that the variable is preserved, you have to call the function again. If you add another
printf("%d\n", fun());
at the end it will print 2 twice, because the value of v2 will be preserved and incremented.
Your second code snippet produces undefined behavior because the function that's declared to return an int doesn't return anything. It's only accidentally returning what you expect -- 2 is the return value of printf(), since it returns the number of characters that it printed (1 followed by a newline), and that's getting left in the location that's used for the return value of the function. Change the function to do
printf("|%d|"\n", v2);
and I expect you'll get different results.
The first code block with the return statement is correct behaviour.
The flow of the program goes this way:
Compiler starts from main()
v1 = v1 + 1; Therefore v1 = 1
You're calling fun() in your print statement --> program control goes to fun():
v2 is initialized
v1 and v2 are incremented, v2 = 1 ; v1 = 2; (This part is actually tricky if the first value in the && statement turned out to 0)
prints 1 to console
returns the value iof v2 which is 1 to the calling function; in this case main()
Control is back to the main; Since you are printing the return value of the function it prints 1
The last statement prints the value of v1 which is 2.
Therefore the output is
1
1
2
In the second block of code, you might have just gotten lucky. The function signature says it returns an int whereas you return nothing. This leads to erratic/undefined behaviour. Unfortunately C as a language doesn't enforce this on the programmer.
For more details on the reasons of this undefined behaviour which is due to an eax register, refer : Function returns value without return statement
I was learning about recursion in C from https://www.tutorialspoint.com/cprogramming/c_recursion.htm and I tried the number factorial example.
#include <stdio.h>
int fact(int i) {
if (i <= 1) {
return 1;
}
return fact(i - 1);
}
int main() {
int i = 3;
printf("numb = %d", fact(i));
return 0;
}
After I executed the code it printed 1. I reviewed the code and found that I forgot to multiply var i with fact(i - 1) at the end of the function. I fixed it and got the correct factorial, but why is fact(3 - 1) equal to 1?
Edit
I had a very shallow understanding of recursion when i posted this question,i thought fact(i-1) would just execute once and didn't get the meaning of calling the function again in the tutorial and i didn't understand it at first when i read the busybee's answer i think i get it now fact(3-1) called fact(2-1) value of var i is now 1 and it satisfied the if condition and returned 1. Another question in the correct version where i multiply var i with fact(i-1) when i change return 1 to return 2 why does it return 12, from the pattern of return 1 and return 2 it seem to multiply 6 result of the function fact with the number in return why? i admit i did no research on what return does and just kinda went with the flow.
To compute the factorial recursively, i must be a positive integer. So that either the value of i is 0 or 1 the factorial will be 1.
If not, then call the recursive factorial algorithm with (i - 1) then multiply the result by i and return that value as shown:
#include <stdio.h>
int fact(int i)
{
if (i ==1)
return 1;
return fact(i - 1) * i; // You forgot to multiply i here
}
int main(void)
{
int i = 3;
printf("Number = %d", fact(i)); // Displaying the factorial of 3
return 0;
}
fact(3 - 1) returns 1 in your first and erroneous version, because it called fact() with i with 2.
This is not less or equal to 1, so fact() is called with 2 - 1. Now this is less or equal to 1, and 1 is returned.
This result is unchanged returned again, and finally once more returned to main().
As a list:
main() calls fact(3).
fact(3) calls fact(2), because its i is 3 and so greater than 1.
fact(2) calls fact(1), because its i is 2 and so greater than 1.
fact(1) returns 1 to fact(2), because its i is less or equal to 1.
fact(2) returns the 1 returned from fact(1) unchanged to fact(3).
fact(3) returns the 1 returned from fact(2) unchanged to main().
main() prints the 1 returned from fact(3).
Edit:
When you're in doubt how your functions are called and what they do, use a debugger (best approach) or insert some printf() (poor man's debugging, but quite easy), like this:
int fact(int i) {
printf("fact(%d) begins ...\n", i);
if (i <= 1) {
printf("... fact(%d) returns 1 because of %d <= 1\n", i, i);
return 1;
}
#if 1 // just temporarily
printf("... fact(%d) calls fact(%d)\n", i, i - 1);
int r = fact(i - 1);
printf("... fact(%d) returns %d\n", i, r);
return r;
#else
return fact(i - 1);
#endif
}
Edit 2:
You might have missed some important things in the lesson on recursive functions.
Each function has its own set of parameters and local variables.
In general, a recursively called function does not have any insight in the local variables or parameters of the calling function.
A recursively called function returns to the calling function. (Some compilers might optimize a "tail call" into a "tail jump", though.)
Can some one explain the execution of this program .
OUTPUT is:
1
2
3
4
3
2
1
how does function retain value 3,2,1 in the end
main(){
int h=0;
g(h);
}
g(int n){
n++;
printf("%d\n",n);
if (n ==4)return 88;
g(n);
printf("%d\n",n);
}
You are getting the above output because at the 8th line of your code you are calling the function agian recursively so the remaining code after the 8th line is saved in the call stack in your memory. So, when you get the output 1 2 3 4, the remaining code that is left (in call stack) is executed hence you are getting this output.
below is the call stack of your program
when n = 0 the stack will place 1
|___|
|___|
|_1_|
when n = 1 the stack will place 2
|___|
|_2_|
|_1_|
when n = 2 the stack will place 3
|_3_|
|_2_|
|_1_|
when n = 4 the stack will not place anything as it encounters the return statement
now, we have some values in our stack
so the program starts popping the top most value in stack (here n = 3) and continue the execution where it left off (i.e it will print the value) and this process will go on until the stack is empty.
NOTE: You can visit this video to understand more effectively about recursion https://www.youtube.com/watch?v=Mv9NEXX1VHc
g(int n){
n++;
printf("%d\n",n); // n=1 print 1 & call g(n) with 1 now g(1) make its own n=2 print 2 & call g(2)
//... print 3 & call g(3) becomes 4 print 4 return 88
if (n ==4)return 88;
g(n);
// now after the return we get back to the 3rd call that called g(3)
//so it print 3 at the end 3 ends
//we go back to the one that called g(2) so we print 2 at the end... & same for 1
printf("%d\n",n);
}
You can read above answers they are pretty good, but here is another way to get you head around it. Simplest answer is the same way that caller function retains its value when calling any function. For example if you have:
int main (void) {
int a = 5;
fun1 (a);
}
void fun1 (a) {
fun2 (a);
printf("%d\n", a); // output would be 5
}
void fun2 (int a) {
a+=1;
fun3 (a);
printf("%d\n", a);
}
void fun3 (int a) {
a+=1;
printf("%d\n", a);
}
So fun1 () would print out 5, fun2 () 6 and fun3() 7. Recursion function is similar to above from perspective of caller and called function, instead of calling function with different name it is calling the function with same name, or in other words it is calling itself.
Look at this code:
void recFun (int a) {
if (a > 6)
printf("%d\n", a);
recFun (a + 1);
printf("%d\n");
}
Some people when I was in school would rewrite above to following (on a piece of paper of course this would yell at you if you try to compile it):
void recFun (int a) {
recFun (a + 1);
printf("%d\n");
}
void recFun (int a) {
recFun (a + 1);
printf("%d\n");
}
void recFun (int a) {
printf("%d\n");
}
In C the function arguments acts as local variables inside the function. Further C uses call-by-value which means that the value of variable used by the caller as argument is copied to the functions argument variable. Consequently the two variables are completely independent variables.
Consider this code:
void foo(int x)
{
x++;
printf("%d", x);
}
void bar(int y)
{
y++;
printf("%d ", y);
foo(y);
printf("%d", y);
}
bar(0);
This will output "1 2 1"
Most people find that it's obvious that changes to x will not change y. They are by name two different variables. So no surprise in that.
If we change the code to use the same name for variables - like:
void foo(int x)
{
x++;
printf("%d", x);
}
void bar(int x)
{
x++;
printf("%d ", x);
foo(x);
printf("%d", x);
}
bar(0);
The output is still "1 2 1"
Simply because the variable x inside foo is another variable than x inside bar. The only relation ship they have is that x inside foo is initialized with a copy of the value of x inside bar. No matter what kind of change you make to x inside foo it will/can not change x inside bar.
Exactly the same goes for the recursion. Each function call creates its own variable n - completely independent of the n variable in previous calls.
Most implementations use a stack for implementing this functionality. Do a search for "stack frame" to get more information. Also see
Explain the concept of a stack frame in a nutshell
void foo(int n, int sum)
{
int k = 0, j = 0;
if (n == 0) return;
k = n % 10;
j = n / 10;
sum = sum + k;
foo (j, sum);
printf ("%d,", k);
}
int main ()
{
int a = 2048, sum = 0;
foo (a, sum);
printf ("%d\n", sum);
getchar();
}
For me this should be 4,0,2,8,0
However, when i execute it, it gives me 2,0,4,8,0
As the code stands, the argument sum to foo is not really relevant since it is passed by value so the last statement in the main function printf ("%d\n", sum) will print 0 regardless of what happens inside foo. That's the last 0 you see in the output the program generates.
Now, the function foo itself accepts an argument n, performs integer division by 10, and recursively calls itself until n is zero. This in effect means that it will print the decimal digits of the input number which is what you see in the output...
It is called as recursive call to the function.
And internally Recursion run as a stack LAST IN FIRST OUT kind
Now in your case it is first printing the output of last call to foo function
Steps in which your program is executing are like this and result will go in stack
1 - 1 st call to foo value of k = 8
2 - 2 nd call to foo value of k = 4
3 - 3 rd call to foo value of k = 0
4 - 4 th call to foo value of k = 2
And as told earlier it will work like stack so the output of the program will be
2 0 4 8 and if you want 4,0,2,8,0 this as a output you need to write the logic accordingly :)
Yes, the output you are getting is absolutely right.
In main(),foo() is called with a=2048 and sum=0.
In foo() we have n=2048, then the if condition calculates values for k,i.e.,(n%10) and j,i.e.,(n/10) till n becomes equal to 0.
Now since there is a recursive call to foo() with j and sum as parameters, the value of k in each iteration gets pushed to a stack and is popped out when n==0 condition is satisfied.
So, if you trace out the program you get values of k=8,4,0,2 which is pushed to stack in the same sequence and thus while popping the elements we have 2,0,4,8.
I usually program in java and recently watching some c codes.
I came up across this program and I don't know how this pointer thing is working.
I know pointer stores the address and all but couldn't make it through the program.
Please tell how is the output coming as 8 ?
#include <stdio.h>
int fun(int n, int * f_p) {
int t, f;
if (n <= 1) {
*f_p = 1;
return 1;
}
t = fun(n - 1, f_p);
f = t + *f_p;
*f_p = t;
return f;
}
int main() {
int x = 15;
printf("%d\n", fun(5, &x));
return 0;
}
What you have here is a recursive function that calculates the i-th element of a Fibonacci sequence (indexing from 0). Each recursive iteration returns two values: the i-th Fibonacci number and the (i-1)-th (previous) Fibonacci number. Since a function in C can only return one value (well, unless you use a struct as return type), the other value - the previous Fibonacci number - is returned to the caller through a pointer parameter f_p.
So, when you call fun(5, &x), the function will return 8, which is the 5-th Fibonacci number, and it will also place 5 into x, which is the previous (4-th) Fibonacci number.
Note that the initial value of x does not matter. That 15 does not play any role in this program. Apparently it is there as a red herring.
If you know what a Fibonacci sequence is, you know that the next element of the sequence is the sum of the two previous elements. This is why the function is written to "return" two elements of the sequence to the caller. You might not care about that previous value in the top-level caller (i.e in main), but the nested recursive calls do need it to calculate the next number. The rest is pretty straightforward.
Step by step:
fun gets called with a 5 and the x address
fun calls fun with a 4 and f_p, which is the x address
fun calls fun with a 3 and f_p, which is the x address
fun calls fun with a 2 and f_p, which is the x address
fun calls fun with a 1 and f_p, which is the x address
fun got called with a 1 so the if condition is true, puts a 1 in the variable pointed by f_p(x) and returns 1
this returned value is assigned to the t of the fun(2,f_p), f is f = t + *f_p which is 1+1 -> f=2;
the variable pointed by f_p is set to t so x=1, returns f so it returns 2
this returned value is assigned to the t of the fun(3,f_p), f is f = t + *f_p which is 2+1 -> f=3;
the variable pointed by f_p is set to t so x=2, returns f so it returns 3
this returned value is assigned to the t of the fun(4,f_p), f is f = t + *f_p which is 3+2 -> f=5;
the variable pointed by f_p is set to t so x=3, returns f so it returns 5
this returned value is assigned to the t of the fun(5,f_p)(the first call to fun), f is f = t + *f_p which is 5+3 -> f=8;
the variable pointed by f_p is set to t so x=5, returns f so it returns 8, which is what the printf prints
Another answer revealed this to calculate the fibonacci numbers using a useful technique for returning an extra value. I've rewritten the code in what I think is a much more understandable and maintainable manner. Hope this prevents people thinking you need to write terrible code to do something like this
#include <stdio.h>
int fib(int n) {
// This is used to return the previous fib value
// i.e. fib(n - 1)
int prevValRet;
return fibRec(n, &prevValRet);
}
// *prevValRet contains fib(n-2)
int fibRec(int n, int *prevValRet) {
// Termination case
if (n <= 1) {
// return fib(0) and fib(1) as 1
*prevValRet = 1;
return 1;
}
// Calculate fib(n-1)
int prevVal = fibRec(n - 1, prevValRet);
// Calculate fib(n) = fib(n-1) + fib(n-2)
int thisVal = prevVal + *prevValRet;
// Return fib(n-1) and fib(n)
*prevValRet = prevVal;
return thisVal;
}
int main() {
printf("%d\n", fib(5));
return 0;
}
As these things go, it's technically straightforward, but...stupid, in the sense that nobody should do things like this. It's a bad use of recursion and badly-written recursion, given the side effects.
The original call of fun(5, &x) isn't going to trip the condition. So, it'll recurse four times (5-1, 4-1, 3-1, 2-1). That's your base condition, which has the effect of setting the pointed-to location (the original x) to 1 and returning 1.
Then we unroll the four calls, each time adding the returned value to the thing at the pointer and changing the thing at the pointer to be that sum.
In simple English, you're doubling one three times.
Edit: As pointed out, I misread the code as assigning f to *f_p rather than t. That makes it a Fibonacci counter.