Shubham Shrivastava Shubham Shrivastava - 1 month ago 6
C Question

Explain the output of following code?

void count(int n){
static int d=1;
printf("%d",n);
printf("%d",d);
d++;
if(n>1) count(n-1);
printf("%d",d);
}
int main(){
count(3);
}


I'm new to programming,so please help me understand,why the output contains two more 4's even after the 'if' statement is false and the function is not recursively invoked after that?

Answer

When you make a recursive call, you do not transfer control over to the function being called forever. If there is some unfinished work in the function making the call, it would get control back to finish the unfinished work once the recursive invocation is over.

In your case, the "unfinished business" is the last printf call. There are three invocations of count. Once the third invocation exits, the second one prints d, which is 4, and exits. This, in turn, gives control back to the first invocation, which prints 4 again.

Comments