C++ Recursion – Printing a Sequence of Numbers in Reverse

Printing a sequence of numbers in reverse


Below is an example of how to reverse a sequence of numbers printed using a recursive function in C++.

10 9 8 7 6 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10

Printing numbers using recursion


To understand how to print a sequence of numbers in reverse, we first demonstrate a recursive function that displays a sequence of numbers in decreasing order.


void print(int n) {
    if ( n <= 0 ) return; //Terminating condition

     cout << n << " "; //Prints number n

     print(n-1); //Calls itself with (n-1)

     return; //Returns from the function
}

The code above is explained in Introduction to Recursion in C++.

Example:

 print(3); 

Produces:

3 2 1

Printing Numbers in Reverse


Now, how would you print out the previous sequence of numbers but in reverse order using recursion?


Think about it. The difference from the previous question and this one is the order in which the numbers are printed. This only requires a simple modification from the previous example.


Hint: Try moving your printing statement around your function.


Related Posts

1 Star2 Stars (4 votes, average: 4.00 out of 5)

View Comments to “C++ Recursion – Printing a Sequence of Numbers in Reverse”

  1. i copied this code and my output ended up being for print(5) 43215

  2. I updated the function name, it might solve your problem.

    What is happening is that your recursive function to reverse a sequence of numbers, is calling a similar recursive function to print numbers in a decreasing order (not reversed).

blog comments powered by Disqus