Friday, August 31, 2007

Programming: Recursion

The need to execute a set of code multiple times is common in programming. Loops are the way we accomplish this task. Sometimes though, the logic to use a loop is not readily obvious. This is where recursion comes into play.

Recursion is calling of a method by itself. In this case, there is a selection statement in which at least one of the choices results in calling the method again, often with new parameters. There is also a case where the method does not call itself, which is used to end the recursion.

Recursion works like a stack of cards. Each call to the method is a card on the stack. When a call is made, the card is put on the top of the stack. Once the ending case is reached, the method calls are resolved from the top of the stack to the bottom. So the first call to the method is the last call that is evaluated.

All recursion can be done with loops instead, but sometimes it is easier to write a recursive method that accomplishes the same task. Many times you can write ten lines of recursive code for twice as many lines of loop code. The drawback to using recursion is that all those method calls take up a lot of memory. So often in private companies, recursion is not used because speed is an issue. Another drawback is that writing recursive code is not straightforward, so maintaining recursive code is difficult.

No comments: