Originally posted by Bob Graffagnino:
The output of this program is baffling me! Can anyone explain the output?
This outputs:
myMethod() 0
myMethod() 1
myMethod() 2
myMethod() 3
myMethod() 3
myMethod() 2
myMethod() 3
myMethod() 3
Nothing aids understanding recursion like a piece of paper and a pencil. Let me try with a computer and a keyboard.
First, we call myMethod (we'll call this activation 1) with a value of 0.
Activation 1 prints: myMethod() 0. It then goes into the for loop and increments i to 1. It then calls myMethod() with a value of 1 (We'll call this activation 2).
Activation 2 prints myMethod() 1. Process coninutes creating activation 3 and 4 and printing out the next two lines.
In activation 4, i is now 3. The line myMethod() 3 is printed, but the for loop fails on the first try. Now, we can go back to activation 3.
When we left activation 3, i was 3. Execution picks up after the recursive call to myMethod() so we'll
test the for loop again. The test fails and this activation of myMethod() completes.
Now, we're back to activation 2, where i is 2. Once again, execution picks up after the recursive call to myMethod(), so we test the for loop. The test succeeds and a new activation (activation 3a) is created with i = 3.
Activation 3a prints myMethod() 3 and then terminates, going back to activation 2. Activation 2 terminates and goes back to activation 1, where i is 1. The process continues until finally, in activation 1, i = 3 and execution completes.
When you're dealing with recursion, draw an activation record stack and follow the flow. It makes life much easier. I sure wish I had a pencil and could draw it for you here.
I hope this clears things up a bit,
Corey