< 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 Numbers in Reverse


By placing the printing statement after the next function call, you reverse the sequence of numbers printed.

void printrev(int n) {
    if ( n <= 0 ) return; //Terminating condition
         
    //Previous location of our print statement

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

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

     return; //Returns from the function
}



Example:

 print(3); 

Produces:

1 2 3

How does this work? By placing the printing statement after the function call, the print statement will execute once all the previous functions finished executing. A diagram explaining this is below.

recursionClick to enlarge


This not only works by printing a sequence of numbers in reverse, it can also be applied to data structures such as vectors when using recursive functions.

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