< Browse > Home / C++ / Blog article: C++ Recursion – Printing a Sequence of Numbers in Reverse

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

November 6th, 2009 | 2 Comments | Posted in C++ by Diego

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.

Pages: 1 2



Leave a Reply |

Related Posts to C++ Recursion – Printing a Sequence of Numbers in Reverse

Follow Discussion

2 Responses to “C++ Recursion – Printing a Sequence of Numbers in Reverse”

  1. mark Says:

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

  2. Diego Says:

    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).

Leave a Reply