Introduction to Recursion in C++

Recursion in C++ is simply a function that calls itself that terminates when a base case is met. It’s very useful to learn how recursion for a couple of reasons.

  • It’s easier to solve certain problems with recursion as the resulting code is usually shorter
  • Sometimes its the only way

Displaying numbers recursively

So what’s an example of a recursive function? Let’s make one. Let’s start by creating a function that displays a number (it isn’t the best example, but it’s good enough to introduce you to recursion).

Display Function

1
2
3
4
5
void display(int n) 
{
     cout << n << " ";
     return;
}


All this function does is simply print the number passed in.

Recursive Display Function

Now let’s have this function call itself but lets decrement the value being displayed each time.

1
2
3
4
5
6
void display(int n)
{
     cout << n << " ";
     display(n-1); //Will call display but with (n-1)
     return;
}

So let’s say we executed display(10)

What would this display? It would display 10 9 8 7 6 5 4…and would never stop. Why? We never told the function when to terminate. This will either cause your program to run until you kill it, or may cause it to segmentation fault. In order to fix this, this calls for the addition of base case.

Base Cases in Recursion

In order for your recursive function to terminate you always need a base case. You may have multiple base cases.

Recursive Display Function with a Base Case

Let’s make the function terminate when n is 0. Or better yet, let’s make it terminate when n is less than or equal to 0. (Why do you think this is better?)

1
2
3
4
5
6
7
void display(int n)
{
     if ( n <= 0 ) return; 
     cout << n << " ";
     display(n-1); //Will call display but with (n-1)
     return;
}

So now, if we execute display(10), what would it display?

10 9 8 7 6 5 4 3 2 1 

How Recursion works in C++

So how does recursion work in C++? Each function creates an activation record on the stack. As a function gets called, it gets added to the top of the stack. Until the function is terminated, is then taken off the stack. A visual example for our display function is below.

Click to Enlarge

(Click to Enlarge)

The first function called was display(10) which is the activation record seen at the bottom of our stack. If you notice, the following function keep getting called as long as the base case isn’t met. Up until n = -1, then the activation record of the functions are popped off.

Comments on Recursion

What is shown previously is a very basic recursive algorithm. More recursion techniques will be discussed later. So even if you don’t understand the purpose of recursion just yet, don’t hesitate. You’ll understand why it’s important when you understand recursion is the only way to do certain problems.

Tags: , , , , , , , ,

  • http://www.collegexperience.net College Experience

    Recursion was really hard for me to understand at first. Just spend time writing out the algorithm and practice using it. It will be a lot simpler to understand =]

  • http://www.collegexperience.net College Experience

    Recursion was really hard for me to understand at first. Just spend time writing out the algorithm and practice using it. It will be a lot simpler to understand =]

  • Diego

    @Eric
    Yes, the worst mistake people tend to do is trying to solve or create recursive solutions in their head. That’s why I recommend drawing things out by hand like the drawing I created. :)

  • raja

    plz give me useful n easy example of recursion.

  • raja

    plz give me useful n easy example of recursion.

  • Diego

    Stay tuned, I’ll be posting examples soon.

  • http://none abby

    ha this was helpful even though i’ve been through it many times.. thanks!

  • Diego

    @Abby

    Thanks for coming. =) If you have anything else you’d like to see just let me know. I plan on visiting these tutorials and changing the structure a bit.

  • Singhashutosh90

    Can anyone please explain how recursion works in case of mergesort.

    MERGE-SORT(A, p, r )if p < r  Check for base casethen q ← (p + r)/2MERGE-SORT(A, p, q)  MERGE-SORT(A, q + 1, r )  MERGE(A, p, q, r )

    In the above algo suppose array is {1,3,2,4,5}. So first mergesort(a,0,2) is passed then does execution proceeds to next line or it waits for result of mergesort(a,0,2). If it does wait then it will again pass (a,0,1) and so on…

    Please explain…

    • http://talkbinary.com Diego Villasenor

      This algorithm goes through the commands sequentially. So it will proceed with mergesort(a,0,2) until it returns a result. So yes, it would be broken down to mergesort(a, 0,1) and would compute that as well.

      *Not sure if it would be 0,1 but you should understand what I’m referring too. Let me know if you have any additional questions. :)