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!

1 comment:

  1. Raas :=
    Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem.

    Graham, Ronald; Donald Knuth, Oren Patashnik (1990).

    ReplyDelete