C++ Recursion – Printing Elements of a Vector

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  vec) { 

     for ( int i = 0; i < vec.size(); i++ ) { 

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

     }

     //Printing end line
     cout << endl;
}


Recursive function for printing elements of a vector


So, how do we go from iteration to recursion? Well if you remember how to Print a Sequence of Numbers using Recursion without a vector, you know at every recursive call we print an number larger than the previous. In this case we want to print out an element in the vector in increasing order. So what would be our function header?

void printVector(vector  vec) { 



Would this work? Well if you think about it, which element would you print? Using iteration, we used the i variable to print the ith element in the vector. Using recursion, we would simply pass this variable, so our function header would be the following.

void printVector(vector  vec, int i) { 



Now, using the knowledge of Printing a Sequence of Numbers using Recursion we could apply this to printing a sequence of elements in a vector.

void printVector(vector vec, int i) { 

     //Returning when i is larger or equal to the size
    //of the vector
     if ( i >= vec.size() ) {
          return;
     }

     //Printing the ith element of the vector
     cout << vec[i] << " ";

     //Calling the function with a larger i
     printVector(vec, i+1);
}



Using this function would be done using the following.

vector  vec; 

//Populate vector...

//Calling the printVector function
printVector(vec, 0);


Have any questions? Feel free to ask below or request any other examples.

Going further


  • 1. How would you make this function's base case take care of another case where your program might crash? (Hint: What is your function was called with a different i value?)
  • 2. How would you make this function be called by simply passing in the vector and not the element to be printed first (in our example, 0). (Hint: Use Helper functions)
  • 3. How would you print the elements of the vector in reverse? (Hint: Printing a sequence of numbers in reverse)

Tags: , , , , , , ,