DEBANJAN GHOSH
DEBANJAN GHOSH

Reputation: 9

C programming , recursion

#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?

Upvotes: 0

Views: 79

Answers (3)

Marco
Marco

Reputation: 2897

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.

Upvotes: 1

klutt
klutt

Reputation: 31296

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

Upvotes: 1

HARSH MITTAL
HARSH MITTAL

Reputation: 760

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

Upvotes: 1

Related Questions