|
-
April 12th, 2008, 03:58 PM
#1
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);
}
-
April 12th, 2008, 04:39 PM
#2
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);
}
-
April 12th, 2008, 04:45 PM
#3
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 ...
-
April 13th, 2008, 07:50 AM
#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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|