I dont understand why this is forward recursion:
int count(int x) {
if(x<=0) return 0;
return 1 + count(x - 1);
}
It's a question on a practice exam, and the answer is that its forward recursion. Why is this the case? How could I distinguish between the two?
You're doing an addition after calling yourself. Tail recursion means absolutely nothing can be after
If you understand the implementation, it's clear why.
Say we call count
for the first time from main
, which is at program counter 0xAAA
. It then does most of its method. We'll say the recursive call to count is at 0xBBB
for this stack frame. If you're using tail recursion, when calling itself, it can set the return address as 0xAAA
(just go straight to the code that called me). If it's doing anything after, it must set the return address as 0xBBC
(the address of the addition). Because it doesn't need stack frames to store return addresses, it's also much easier to transform the recursion to iteration. When count
calls itself, it can just jump to the beginning of the method.
The solution (to the trivial example) is to build up the result in another parameter:
int count(int x, int res) {
if(x<=0) return res;
return count(x - 1, res + 1);
}
Note we do nothing after.
Did you look at this SO question, tail vs forward recursion?
Matthew has the answer,and the long form would be that:
int count(int x) {
if(x<=0) return 0;
return 1 + count(x - 1);
}
can be written as (and is expanded as something like):
int count(int x) {
if(x<=0) return 0;
int tmp_result = count(x - 1);
return 1 + tmp_result; // e.g. recursion is not last
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With