Writing a Recursive Function

working with laptop 4

Every time I go to write a recursive function, and I’ve written a few, I have to think it out.

For those of you that aren’t familiar with recursion, the idea behind recursion is that the function that’s currently being executed calls itself until a certain condition is met.

Here’s a short example:

public static int CountToTen(int CurrentValue)
{
  if(CurrentValue != 10)
  {
     Console.WriteLine("CurrentValue: {0}", CurrentValue);
     CurrentValue = CountToTen(CurrentValue);
  }
  return CurrentValue;

public static void main()
{
  Console.WriteLine("Value Should Be 10: {0}", CountToTen(0));
}

Of course this is a rather elementary function, and I’m sure that you’d just rewrite the “CountToTen” function as a for loop, but that wouldn’t be a good demonstration now would it?

Why Use Recursion?

So, what are some real work applications of recursion?

One of them I’m working through right now.  I have a collection of data rows that need to be shown as a tree.  To do this, each of the rows have an id and a parent.  What I need to do is to go through the list and assign rows to parents if they have one, and to get a list of children so that I know who belongs to whom.

In this case, I use recursion so that I can go through the list, create the object that represents the row, and then see if there are any other rows that are children of this row.  When I’m finished, I’ll have a list of objects, and it’ll be relatively little code, but it’s one of the more complex operations in code that one will write–and test well to get it right.

Ingredients

To write a good recursive function, you must start with what you want to get out of it.  What’s the goal?  Is recursion the best way to get that result?

After you’ve made that decision, figure out how you’ll know you’re done.  This is critical, otherwise you’ll just keep calling the function over and over.

Last, figure out what has to be passed to the function in order for it to be operated on–you’ll probably have to have another function kick it off with the right starting point.

Leave a Reply

Your email address will not be published. Required fields are marked *

CommentLuv badge