Tail/forward recursion in Java -


i dont understand why forward recursion:

int count(int x) {     if(x<=0) return 0;     return 1 + count(x - 1); } 

it's question on practice exam, , answer forward recursion. why case? how distinguish between two?

you're doing addition after calling yourself. tail recursion means absolutely nothing can after

if understand implementation, it's clear why.

say call count first time main, @ program counter 0xaaa. of method. we'll recursive call count @ 0xbbb stack frame. if you're using tail recursion, when calling itself, can set return address 0xaaa (just go straight code called me). if it's doing anything after, must set return address 0xbbc (the address of addition). because doesn't need stack frames store return addresses, it's easier transform recursion iteration. when count calls itself, can jump beginning of method.

the solution (to trivial example) build result in parameter:

int count(int x, int res) {   if(x<=0) return res;   return count(x - 1, res + 1); } 

note nothing after.


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -