Wednesday, April 20, 2011

Recursive Function Design 101

Everyone has his approach to how to start writing a function. For a recursive function as soon as you identify that the problem can be simplified by recursion, heres how you should structure your code :

  • First write for the simplest case and return. This would be the boundary condition on the function call. e.g. for factorial write the code for case when input == 0 || input == 1  
  • Build up from there. 
Basically if you put down the simplest case first and test it so you are sure it is reliable writing the rest of the recursive function becomes super easy. 

Enjoy!