Reputation: 31
In the code given, the output that I can think of is 3122134 because the the last printf statement gets executed only once when n=1. so condition become 1>1 which is definitely not true and the loop exits and the last printf statement is executed. but the original output is 312213444. Why is it so ? Where am I going wrong ? kindly explain every concept and instance of it ?
#include <stdio.h>
void count (int n)
{
static int d=1;
printf("%d", n);
printf("%d", d);
d++ ;
if(n>1)
count(n-1);
printf("%d", d);
}
void main ()
{
count(3);
}
Upvotes: 0
Views: 101
Reputation: 39316
Rewrite your printf()
statements (and fix your main
declaration), for example into
#include <stdlib.h>
#include <stdio.h>
void count(int n)
{
static int d=1;
printf("A) n = %d\n", n);
printf("B) d = %d\n", d);
d++;
if (n>1)
count(n-1);
printf("C) d = %d\n", d);
}
int main(void)
{
count(3);
return EXIT_SUCCESS;
}
Compile and run the code, and look at the output, and you shall understand.
One technique that can help unravel recursive functions, is to unwrap a couple of the recursive calls into separate functions. Here, main()
calls count(3)
, which does a recursive call count(2)
, which does a recursive call count(1)
. We can change these recursive calls to calls to separate functions by repeating the function three times. We do need to change the d
variable into a global, though, so that each of the function copies uses the same one, instead of separate copies that just happen to have the same name.
#include <stdlib.h>
#include <stdio.h>
int d = 1;
void count1(void)
{
int n = 1;
printf("count1(): A) n = %d\n", n);
printf("count1(): B) d = %d\n", d);
d++;
/* The following is never true, so
we comment it out:
if (n>1)
count0();
*/
printf("count1(): C) d = %d\n", d);
}
void count2(void)
{
int n = 2;
printf("count2(): A) n = %d\n", n);
printf("count2(): B) d = %d\n", d);
d++;
if (n>1)
count1();
printf("count2(): C) d = %d\n", d);
}
void count3(void)
{
int n = 3;
printf("count3(): A) n = %d\n", n);
printf("count3(): B) d = %d\n", d);
d++;
if (n>1)
count2();
printf("count3(): C) d = %d\n", d);
}
int main(void)
{
count3();
return EXIT_SUCCESS;
}
In this particular case, unraveling the recursive function should help understand control flow. (Specifically, that when you call another function, and the function returns, the execution continues in the caller in the statement following the function call.)
Upvotes: 3
Reputation: 1679
As you are recursively calling the function
count()
you are putting each call of count() on the stack of your application. After the last call of count is finished you return to the last call of count, which also prints the static variable d (which is only initialized once) again and so on, until the stack is finally on top and it goes back to the main method. This is why you are getting the last two '4' in your output.
Upvotes: 0