< Browse > Home /

C++ Recursion – Printing Elements of a Vector

February 21st, 2010 | No Comments | Posted in C++ by Diego | - [Full Entry]

Printing elements of a Vector using Recursion


Below is an example of how to print the elements of a vector using recursion. Later, we’ll print the elements in reverse. Why is this useful? You can apply this principle later to more complex data structures such as Binary Search Trees, or Linked Lists.

This tutorial assumes you understand the following:

Iterative version for printing elements of a vector


To understand how to print elements of a vector using recursion, let’s write a simple algorithm that will do it for us using iteration.

void printVector(vector <int> vec) {
   
     for ( int i = 0; i < vec.size(); i++ ) {

          //Printing ith element  followed by a space
          cout << vec[i] << " ";

     }

     //Printing end line
     cout << endl;
}

Read more »

Introduction to Recursion in C++

February 21st, 2009 | 6 Comments | Posted in C++ by Diego | - [Full Entry]

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

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.

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. Read more »