Skip to content

Instantly share code, notes, and snippets.

@anoopelias
Last active December 27, 2015 13:29
Show Gist options
  • Save anoopelias/7333427 to your computer and use it in GitHub Desktop.
Save anoopelias/7333427 to your computer and use it in GitHub Desktop.
Recursion

There are two forms of recursion,

  • Tail Recursion : The return value is calculated as a combination of the value of current subroutine and the return value of the next call. Example,

     int factorial(int a) {
         if(a==0)
             return 1;
         else
             return a * factorial( a-1 );
     }
    
  • Accumulator based recursion : You accumulate the results by adding an additional parameter and return the accumulated value.

     int factorial(int a, int fact) {
         if(a==0)
             return fact;
         else
             return factorial(a-1, a*fact);
     }
    

Tail recursion is considered more readable, while it can cause a StackOverflow!. This is because it has to push the current value to a stack, before calling subroutine again. And when you make a large number of such calls, this stack might go over its limit.

Some compilers optimize tail recursion to accumulator based in order to avoid this problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment