DEV Community

loading...
Cover image for Recursion Illustrated with PseudoCode and Code

Recursion Illustrated with PseudoCode and Code

akintoluvic profile image Vick Greenfields ・2 min read

WHAT IS RECURSION?

The simplest definition of recursion is simply when a function solves a problem by calling itself. Confusing right? Yes and no. I am going to illustrate how recursion works in both real life and in javascript in order to make things clearer.

Alt Text

HUNGER ILLUSTRATION

Imagine that you are hungry now and you will like to eat 'Jollof Rice'. Let us write the solution in pseudo code

 First you need to dish the Jollof Rice
      then you need to eat the Jollof rice
Enter fullscreen mode Exit fullscreen mode

In Javascript, the code will look like this.

function eat(food) {
    dish(food)
    eatFood();
}
if(hungry) {
    eat('Jollof Rice')
}
Enter fullscreen mode Exit fullscreen mode

If hungry is true, to eat, you dish the food and start eating. Simple right?

Except eating is not that simple. It involves carrying the rice with fork and chewing it before swallowing it.

function eat(food) {
    dish(food)
    eatFood()
}

function eatFood() {
    carryForkOfRice()
    chewAndSwallow()
}

if(hungry) {
    eat('Jollof Rice')
}
Enter fullscreen mode Exit fullscreen mode

And then again and again, you carry fork and chew, the process only stops when you are satisfied. One spoonfull can not possible satisfy you right? You need to do it again and again. And that is why recursion comes in, the eat food function has to keep calling itself for the hunger to quench. Which means your eat food function has now gone recursive as it now calls itself over and over.

function eatFood() {
    carryForkOfRice()
    chewAndSwallow()
    eatFood()
}
Enter fullscreen mode Exit fullscreen mode

But just as a computer has a limited memory, in the same way, your stomach can only take a sizeable amount of food. Which means your brain has to check after each for of rice whether you are satiated or not, in order to prevent overfeeding. This we implement by checking if you are satiated after swallowing food.

function eatFood() {
    carryForkOfRice()
    chewAndSwallow()
    if(satiated) {
        return
    } else {
        eatFood()
    }
}
Enter fullscreen mode Exit fullscreen mode

In programming, a recursive function will continue to run perpetually until the computer runs out of memory. To prevent this, a breaking comdition is set. A good example is the if satiated clause condition in our eat food condition above.

Discussion (0)

pic
Editor guide