Ryan Ho

Think, Create, Do, Repeat

LinkedIn GitHub Facebook Twitter

Recursion

December 13, 2015 | Coding

What is recursion?

Recursion is a method that calls itself. The concept of recursion has its origins in Mathematical theory, where there are many examples of expressions written in terms of themselves. One example is the Fibonacci sequence where it is defined as: F(i) = F(i-1) + F(i-2)

Recursion is a useful way to solve certain problems that require less code and better run times

Parts of a recursive algorithm

All recursive algorithms must possess the following:

  1. Base Case (to denote when to stop)
  2. Work towards the Base Case
  3. Recursive call (calling itself)

An example of a recursion method to find the sum of numbers


	    		def recursion_sum(number)
	    			if number == 1
	    				return 1
	    			else
	    				return n + sum(number-1)
	    			end
	    		end
	    		

Overall, recursion is a cool concept to use to solve certain problems, which could prove more effective than iterative methods. I look forward to learning more about recursive methods soon!

Comments box

Name:
Email:
Comments: