C++ Recursion – Printing a Sequence of Numbers in Reverse
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
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.
Click 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


(4 votes, average: 4.00 out of 5)

November 29th, 2009 at 2:27 pm
i copied this code and my output ended up being for print(5) 43215
November 29th, 2009 at 3:32 pm
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).