CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4

Thread: tail recursion

  1. #1
    Join Date
    Aug 2007
    Posts
    28

    Question tail recursion

    hey everyone can please someone tell me why this C function that i wrote is not tail recursive??

    and how would it look like if it was tail recursive...

    also.. is it possible to use a goto function here? if so.. how?

    thank you

    Code:
    int SP(int a[], int i, int n) {
    return (i >= n) ? 1 : a[i] * SP(a, i + 1, n);
    }

  2. #2
    Join Date
    Dec 2006
    Posts
    166

    Re: tail recursion

    it is only tail recursive if the recursive call is the last thing done

    in this case, it still needs to do a multiply after getting the result of the recursive call, so it is not tail recursive

    C does not have tail recursion anyway

    to make it tail recursive, in this case you would keep track of the product "so far" and pass it recursively as an additional argument to the function, something like
    Code:
    int SP2(int a[], int i, int n, int product) {
    return (i >= n) ? product : SP2(a, i + 1, n, product * a[i]);
    }
    int SP(int a[], int i, int n) {
    return SP2(a, i, n, 1);
    }

  3. #3
    Join Date
    Aug 2007
    Posts
    28

    Re: tail recursion

    ohhhh i seee... interesting... thanks for such a quick response

    what about the goto functions.. i read somewhere that i can replace the recursion with the goto ...

  4. #4

    Re: tail recursion

    http://library.readscheme.org/page1.html has the 'lambda the ultimate' papers, which show how recursion can implement procedural constructs.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured