Recursion from a noobs perspective.

Diljeet(DJ) Singh
From WordPress
Published in
3 min readAug 31, 2017

Hey, Hey, Hey thats recursion have a great day.

Nah jk! Recursion is the ability to reuse your functions within its self.

Say what????

Example 1: (Ruby)

Lets look at an example:

Screen Shot 2017-08-30 at 8.35.36 PM.png

As you can see we are calling the method “howRya” within it’s self.

So what is this doing exactly?

  1. It starts of by taking an argument referred to as “questionMark”. Then it prints the whatever was assigned to “questionMark”.
  2. Then it increments the second argument called “counter”.
  3. Then we get to line 4 where we have a conditional that we check to see if the value of counter is less than 10. I started with a counter as you can see below.
Screen Shot 2017-08-30 at 8.34.54 PM.png
  1. Now since the conditional is true since 0 is less than 10. We go to the next line and call “howRya” again.

What this is going to do is pass the same “?” and our counter (our incremented counter). Since we are calling our function within its self we are going in “down on stack”. Now as this program will run again we will still have our “?” but now our counter has been incremented from 0 to 1. And this time around it will go from 1 to 2 and so forth.

Pretty cool right!?!?

What do you think output will be? Let’s not forget that as you are going down a stack the original function that you started with has not finished executing.

Because of this we will print all of our “?” before we print “how are you doing?”

Screen Shot 2017-08-30 at 8.46.08 PM.png

Very cool!

Cons of Recursion:

  • Slow

Recursion is slow compared to iteration. Why? As you recur and go down stacks your program still has to manage the original loop while it continues to run through the stacks.

Why use Recursion:

  • Badass (Less Code)

I mean come on that code up there was pretty badass. As you typically need to write less code when you use recursion.

Rules of Recursion:

  1. Base Case.
  2. Must make progress towards the base case.
  3. Must call its self.

It is very important to make progress towards your goal. If you do not you will likely end up with an error stating your “call stack is too deep”. What the error means is your computer is unable to go down further stacks as there is no way out. Basically a hole with no end.

The Base Case is important because as your program digs deeper it needs to remember what its purpose is.

References:

Laws of Recursion

Khan Academy

Recursion

--

--