I would like some help understanding the following code :
#include <stdio.h>
int func(int z, char a);
int main(void)
{
func(4,'a');
} // end main
int func(int z, char a)
{
if (z==1)
{
printf("%s", "last\n");
return 1;
} // end if
func(z-1,a);
printf("%d\n", z,a);
} // end func
The output is:
last
2
3
4
However, if you put the last printf above the last recursive function call, the output is
4
3
2
last
Why the reversal?
In the first instance, I can understand that the number 4 passed to the function (func) is then repeatedly reduced when the recursion calls itself (z-1) until it reaches βlastβ and then prints the output below.
But, where does the 2 come from?
If someone could help me trace the four through the various functions I would be most grateful.
Because when the print statement is above the function call, it prints and then calls the function:
call function with β4β. print β4β ; call function with β3β, print β3β, call function with β2β, print β2β, call function with β1β, print βlastβ, return, return, return, return
And when the print statement is below the function call, it calls the function recursively, until z becomes 1, and then returns back to each previous call and prints the z value of that call :
call function with β4β, call function with β3β, call function with β2β, call function with β1β; print βlastβ, return, print β2β, return, print β3β, return, print β4β, return
Ok, but if you put the function statement both above and below the printf statement (i.e. the printf statement βsandwichedβ between them. You get the following output:
last
2
last
3
last
2
last
4
last
2
last
3
last
2
Which does not follow your logic above? Why all the bizarre mix?
ps - I am running a little deeply into recursion with these simple examples as I really want to get my head around it.