Introduction to Recursion

A Simple introduction to recursive methods. Emphasis on using java, but the theory can be applied in other languages as well.

To someone who has never attempted writing recursive functions before, the thought of learning may be daunting at first.  I remember when my professor first implied that we were to learn about recursion next week and then thinking to myself “I need to make sure I’m awake for that class.”  However, recursion is not nearly as difficult as it first sounds to be.

A recursive function is simply a function that will call itself in order to solve a problem.  They really are not that difficult, the only thing you have to worry about is making sure you have a way to stop the loop before it becomes infinite, and we will discuss this later.

Java Code (simple example of a recursive function that returns true)

public boolean recusiveFunction(int i){

if(i <= 0)

return true;

else

return recursiveFunction(i-1);

}

Above is a simple java example of a recursive method that takes one input (an integer) and will continue to call itself (and each time decrease i by 1) and then return true.

The way the above example would work is you call the recursive function by calling recursiveFunction(5) (note: 5 could be any integer).  When you call the function it will go to the first if statement as normal.  If the variable i is less than or equal to 0, the function will return true.  In this case, 5 is greater that 0, so it returns recursiveFunction(4) (5-1 = 4) and goes through the process again.  Because the return value of recursiveFunction(int i) is boolean it will return true or false and we can return that through the recursive stack. 

Base Case

Always remember your base case.  In the above example, the base case is “if(i <= 0){…}”.  It is important to always have a case in your recursive function that will return a defined value so that you will not continually call your recursive function into an infinite loop.  Also make sure your base case will always be reached at one point.  If instead of calling “recursiveFunction(i-1)” I called “recursiveFunction(i+1)”, my base case would be faulty because for some inputs of i, it would never be reached.

Recursive call

A recursive function is not recursive unless it calls itself.  You are allowed to call it in different ways based on different inputs, in fact, recursive functions can have many different behaviors based on the inputs, just make sure you define the behaviors you want.

Leave Your Response