6.1.3 Recursion Example: Reverse String
Take a look at another example, this time with a string. The problem you are trying to solve is to print a string in reverse order.
From your knowledge of loops, you should know that you can print a string in reverse order using a loop, for example:
Output:
This problem can also be solved recursively. Recursion is another form of an iterative statement and you will find that many recursive problems can be rewritten with a for or while loop.
Reverse a String Recursively
In the problem below, notice that the base case when the string length is less than or equal to 1. When the string only has a length of 1, it is the same backward and forwards. The same could be said for a length of 0. Either scenario works for a base case, however, if you do want to consider the case of an empty string, you must cover zero in your base case.
When you are in your base case, you can simply print the string since it is the same backward and forwards.
When you are not in the base case, your recursive call should be to a string one smaller than the current string and then print the first letter.
Tracing Example
Take a look at how this would work if the user entered hello
.
The first call from main
would be:
reverse("hello")
- Not the base case, so the return will callreverse("ello")
. Notice that the return statement will add the letterh
after the recursive call returns.reverse("ello")
- Not the base case. Callsreverse("llo")
.reverse("llo")
- Not the base case. Callsreverse("lo")
.reverse("lo")
- Not the base case. Callsreverse("o")
.reverse("o")
- Base case. Returnso
toreverse("lo")
. Remember this will be the first letter in the return string since all others are waiting on the recursive call to finish.reverse("lo")
returns theo
+ thel
toreverse("llo")
.reverse("llo")
returns theol
+ the otherl
toreverse("ello")
reverse("ello")
returnsoll
+ thee
toreverse("hello")
reverse("hello")
returnsolle
+ theh
to the main function, which then prints the string reversed.
Switching the order
One of the things that is really nice about recursion is that a small change can be made to the program to get very different results. In this example, try switching the order of the recursive call and the substring from:
to
This small change will have a noticeable impact on the code. How could a small change like this impact some of the data structures you have seen?
Last updated