Tail and Non-Tail Recursion
Tail and Non-Tail Recursion
• Tail Recursion?
– Definition
– Advantages of tail recursion
– Converting to and from tail recursion
• Indirect Recursion?
– Definition
– Examples
What is Tail Recursion?
• Recursive methods are either
– Tail recursive
– Nontail recursive
• Tail recursive method has the recursive call as the last statement in
the method.
• Recursive methods that are not tail recursive are called non-tail
recursive
Is Factorial Tail Recursive?
• Is the factorial method a tail recursive method?
• When returning back from a recursive call, there is still one pending
operation, multiplication.
void tail(int i) {
if (i>0) {
system.out.print(i+"")
tail(i-1)
}
It is tail recursive!
Third Example
• Is the following program tail recursive?
• No, because there is an ealier recursive call, other than the last
one,
• In tail recursion, the recursive call should be the last statement, and
there should be no earlier recursive calls whether direct or indirect.
Advantage of Tail Recursive Method
• Tail Recursive methods are easy to convert to iterative.
auxiliary parameters!
int fib_aux ( int n , int next, int result)
{
if (n == 0)
return result;
return fib_aux(n - 1, next + result, next);
}
• P(x) is true, the value of F(x) is the value of some other function
G(x). Otherwise, the value of F(x) is the value of the function F on
some other value, H(x)
F(x) {
int temp_x = x;
while (P(x) is not true) {
temp_x = x;
x = H(temp_x);
}
return G(x);
}
Converting Tail Recursive to Iterative
int fact_aux(int n, int result) { F(x) {
if (n == 1) return result; if (P(x)) return G(x);
return fact_aux(n - 1, n * result); return F(H(x));
} }
decode(buffer)
decode information in buffer;
store (buffer);
store(buffer)
transfer information from buffer to file;
recieve (buffer);
Indirect Recursion:Another Example
• Determine whether an integer is even or odd:
• How do we know if a number is even?
– we know 0 is even.
– we know that if n is even, then n-1 must be odd.
static boolean is_even(int n)
{
if (n==0) return true;
else return(is_odd(n-1));
}