0
#include <stdio.h>

void main(){

    static int n=7;
    
    if(n){
        n--;
        main();
        printf("%d",n);
    }

}

Sol: I was trying to trace the recursion. In my logic answer should be 1234567, but the answer is 000000. My question is how to trace this recursion?

2
  • 2
    Note that n is static. So there's only one of it. And by the time any of the main's start printing it, all the subtractions have been done. Commented Jun 15, 2021 at 19:16
  • @pmg That's the sort of thing that happens when people retype their code here, rather than copying and pasting. Commented Jun 15, 2021 at 19:17

3 Answers 3

1

That is because you are calling main before printing.

if you do:

#include <stdio.h>

void main(){

    static int n=7;
    
    if(n){
        n--;
        // main();
        printf("%d",n);

        main();
    }
    return;
}

You will get the output: 6543210

But in your case, it will print only when the value of n is 0. And since 7 print is pending therefore 0000000

Sign up to request clarification or add additional context in comments.

Comments

1

There exists only one variable since it's static. A slight modification (including the fix of void return type) demonstrates it:

#include <stdio.h>

int main(void)
{
    static int n=7;

    if(n) {
        n--;
        printf("%d",n);
        main();
        printf("%d",n);
    }
}

Output:

65432100000000

Comments

1

The best way to trace it probably is using gdb to follow it along.

If you declare n as static, it's value would be preserved across function calls. Note that you are calling printf after the recursive step (calling main). This causes printf to see the value of n after all the calls to main.

Think of this sequence, executing with n = 2

if (n) // first time, n == 2.
n--; // n == 1
main();
  if (n) // second time, n == 1
  n--;
  main();
    if (n) // third time, n == 0, fails
  printf("%d",n); // n == 0.
printf("%d",n); // n == 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.