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



(3 votes, average: 3.67 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).