Head Recursion
vs
Tail Recursion
Muhammad Saqib Ilyas
Recap
• Memory segments in a modern computer
• Recursion
• A powerful programming approach
• Breaking down a large problem into smaller ones
• Combine results of smaller problem solutions
• Recursive step
• Base case(s)
• Uses stack
Learning goals
• Describe the difference between two recursion
approaches
• Identify whether a given function is head recursive or
tail recursive
• Implement a tail recursive solution to a simple problem
in C
Head Recursion
• Some computation after the recursive call returns
unsigned long factorial(unsigned int n) {
if (n == 1)
return 1;
return n * factorial(n – 1);
}
Multiplication
Consequence
Stack n-1
• The function call stack grows
• Might overflow the stack space
Heap
Block Started by
Symbol (BSS)
Data
Text 0
Address
Tail recursion
• When the recursive call is the last thing a function does
• Example:
int isPalinHelper(char* str, int start, int end)
{
if (end - start < 1)
return 1;
if (str[start] != str[end])
return 0;
return isPalinHelper(str, start + 1, end - “”
1); “bb”
} “abba”
int isPalin(char* str) {
Tail recursion
• Earlier function calls simply return when recursive call
does
• Compilers optimize this by not using unnecessary stack
frames
“abba”
“bb”
“”
Examples
• Find the largest value in an array of integers
• Find the product of two positive integers
• Find the sum of digits in an integer
Recap
• Tail recursion
• When recursive call is the last thing that a function does
• Compilers optimize stack space for tail recursive
functions
• Some problems can be coded in a tail-recursive manner