Computer Science: Recursion Problem

<p>Consider the following recursive method.
public static void whatsItDo(String str) {
int len = str.length();
if (len > 1) {
String temp = str.substring(0, len – 1);
whatsItDo(temp);
System.out.println(temp);
}
} </p>

<p>What is printed as a result of the call whatsItDo(“WATCH”) ?
Could someone explain this problem to me.
Answer:
W
Wa
Wat
Watc</p>

<hr>

<p>I’ve got no idea how to solve this one, I can solve the recurssion problems that deal with numbers, but this one is getting me.</p>

<p>whatsItDo(“Watch”)
len=5, temp = “Watc”
whatsItDo(“Watc”)
len = 4, temp = “Wat”
whatsItDo(“Wat”)
len = 3, temp=“Wa”
whatsItDo(“Wa”)
len=2 temp=“W”
whatsItDo(“W”)
System.out.println(temp)=> prints "W), returns
System.out.println(temp)=> prints “Wa”, returns
System.out.println(temp)=> prints “Wat”, returns
System.out.println(temp)=> prints “Watc”, returns</p>

<p>We’re done!</p>

<p>Thanks ClassicRockerDad, I understand how the substring is broken down into the single “w”, however, I’m not understanding why it’s printing in that oder. W -> WA -> WAT, not Watc -> wat -> wa -> w.</p>

<p>When the base case is met, the last method before the base case prints its string, then the second last method is invoked and so on until the first invocation of the method. </p>

<p>An analogy to this is like climbing up a ladder and then climbing it down, you climb the second tallest step to reach the very top, then when you come down from the very top, you have to climb down the second tallest step to the bottom.</p>

<p>After the base case occurs, control of all the method invocations resume immediately after the method calls, so that all methods print their strings to the console.</p>

<p>^Thanks a lot man. I understand it now!</p>

<p>

</p>

<p>Great explanation!</p>