Printing a sequence of numbers in reverse
Below is an example of how to print a sequence of numbers in reverse.
Given n = 10 the following would be the result of printing a sequence of numbers in decreasing order as long as n > 0.
1 | 10 9 8 7 6 5 4 3 2 1 0 |
The reverse order of this sequence would be the following:
1 | 0 1 2 3 4 5 6 7 8 9 10 |
Using recursion, we will demonstrate how to reverse the order of a sequence by simply manipulating a few lines of code.
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 using recursion.
1 2 3 4 5 6 7 8 9 | 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 following code, simply prints out n while then calling the same print function on n – 1 and stops when n < 0. The code above is explained in more detail in the following tutorial: Introduction to Recursion in C++.
Example:
1 | print(3); |
Produces:
1 | 3 2 1 0 |
As mentioned, the recursive function first prints out n, then calls itself on n – 1 as long as n > 0.
Printing Numbers in Reverse
Now, how would you print out the previous sequence of numbers but in reverse order while still using recursion?
Think about it. The difference from the previous solution and this question 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. Go ahead and try it before you look at the solution.
By placing the printing statement after the function call, you delay printing until n > 0 isn’t true which would be when n = -1. Therefore, this call would terminate, and return to the function call when n = 0, and print 0. This function call would terminate, and return to the function call when n = 1, and print 1, and so on.
1 2 3 4 5 6 7 8 9 10 11 | 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; } |
Example:
1 | printrev(3); |
Produces:
1 | 0 1 2 3 |
A diagram further explaining the following modification 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, string, linked lists, and others when using recursive functions.
