Tutorial 5 – Functions & Recursion

So far we’ve kept all of our code within the one main function. As you can imagine, if we were making any kind of complex program, this would just become one long mess of code. Fortunately C (and C++) allows us to call code from other functions. Let’s look at an example.

int squared(int input) 
{ 
    return input * input; 
}

First in this code we define the squared function. Once defined it can be called in any other function as shown below:

int main()
{
    int twoSquared = square(2);
}

Obviously there are many things that can be done through the use of functions like this. One that we’ll take a look at now is recursion. This is when a function calls itself. For example:

int Fibonacci(int input)
{
    if(input <= 1)
    {
        return input;
    }
    else
    {
        return Fibonacci(input - 1) + Fibonacci(input - 2);
    }
}

int main()
{
    for(int i = 0; i < 10; i++)
    {
        printf("%d\n", Fibonacci(i));
    }
}

In this example we have a function which will return the value at a given point in the fibonnaci sequence. It does this by continually calling itself with a slightly smaller problem (in this case the last 2 fibonnaci terms) until it reaches the base case (for fibonnaci this is an input value of 1).

Recursive code is a very powerful tool and if done right can simplify computational problems no end!

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Tell me what you think!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: