Menu

What is a recursive function?

June 18, 2019 - General, C Language, Python
What is a recursive function?

 
 
 
 
 
 
 
 
 
You have probably already heard the term “recursive function” but if you are very new to programming it is maybe the first time you hear it. Many beginners in programming see recursive functions has a very complex and abstract topic but I will show you that it is in fact very simple.

First of all a recursive fonction is a fonction that calls itself. It can be very similar to a loop… the function will execute a bunch of instructions many time by calling itself repeatedly. In some case you will prefer using a recursive function instead of a loop. Lets see a first example in C language:

#include <stdio.h>

int myFunc(int i) 
{  
    if(i < 10)
        myFunc(i + 1);
    printf("Hello world!\n");
}

int main() 
{
  myFunc(1);

    return 0;
}

Just above you can see a very simple example of a recursive function, lets detail the code a little bit:

int myFunc(int i) 
{  
    if(i < 10) // if i is smaller than 10 we call the function taking i+1 in parameter
        myFunc(i + 1); // if we set i to 1 when we call the function it execute the code 10 times
    printf("Hello world!\n"); // print "Hello world!" at the end of the function
}

Most languages support recursive functions and it is always the same thing, (only the syntax changes) it is a function that execute a set of instructions repeatedly by calling itself. Here we tested in C but you can easily test this code in python:

def myFunc(i):
    if i < 10:
        myFunc(i + 1)
    print("Hello world!");

myFunc(1)

This is the exact same code in python, (yes the code is way simpler in python) the output should be:

Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!
Hello world!

This article was really to show you what is a recursive function. Now, start with this code and play with it, make it print an array, make it execute itself 100 times instead of 10… Try to create your own recursive function. Even if it seems abstract, when you will get use to it you will see that it can be very useful in some situations!

Written by Samuel Gauthier

Leave a Reply

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