recursion and stack----help banfa

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jerico
    New Member
    • Sep 2006
    • 39

    #1

    recursion and stack----help banfa

    Hi.I know that recursion uses stack and a recursive function call itself until a terminating condition is satisfied.But i get problem in visualizing them..for example how the following program is executing...

    void fun(int);
    int main()
    {
    int a=3;
    fun(a);
    return 0;
    }
    void fun(int a)
    {
    if(a>0)
    {
    fun(--a);
    printf("%d",a);
    fun(--a);
    }
    }

    the program outputs 0 1 2 0.thanks for any help.

    jerico
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Well follow it through on paper listing the function calls that each function makes and parameter values or specificaly the value of a at each call, indenting for call depth (Note DC = Don't Care)

    Code:
    main(DC)
       fun(a = 3)
          fun(a = 2)
             fun(a = 1)
                fun(a = 0)
                printf(a = 0)
                fun(a = -1)
             printf(a = 1)
             fun(0)
          printf(a = 2)
          fun(1)
             fun(a = 0)
             printf(a = 0)
             fun(a = -1)

    Comment

    Working...