Click to See Complete Forum and Search --> : tail recursion


eidalina20
April 12th, 2008, 03:58 PM
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


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

spoon!
April 12th, 2008, 04:39 PM
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
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);
}

eidalina20
April 12th, 2008, 04:45 PM
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 ...

pm_kirkham
April 13th, 2008, 07:50 AM
http://library.readscheme.org/page1.html has the 'lambda the ultimate' papers, which show how recursion can implement procedural constructs.