tags:

views:

91

answers:

2

I was trying to write recursion function,to find factorial of a number.

    int factorial(int input,int *answer)
    {
       if ( input ==0 )        
       {                       
        return 0;
       }

       *answer  = *answer * input;
       factorial(input -1, answer);
    }

What will you say about this function? Is it tail recursive?

+2  A: 

Here's a link with a definition: http://phoenix.goucher.edu/~kelliher/cs23/feb21.html

"A function is tail recursive if the very last thing it does is make its recursive call."

In the code you posted, the last thing the function does is make a recursive call to itself, so by this definition, it is tail-recursive.

Rice Flour Cookies
A: 

When doing tail recursive functions (especially tail recursive functions) it is often helpful to have a helper function in addition to another function which has a more friendly interface. The friendly interface function really just sets up the less friendly function's arguments.

static unsigned factorial_helper(unsigned input, unsigned acc) {
       if (intput == 0) {
           return acc;
       }
       return factorial_helper(input-1, acc * input);
}

unsigned factorial(int input) {
    if (input < 0) {
        do_something_bad();
    }
    return factorial_helper(input, 1);
}

By passing an accumulator value you avoid having to use pointers or do any computations upon returning from called functions, which makes the functions truely tail recursive.

nategoose