programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Liutauras Vilda
• Jeanne Boyarsky
• Devaka Cooray
• Paul Clapham
Sheriffs:
• Tim Cooke
• Knute Snortum
• Bear Bibeault
Saloon Keepers:
• Ron McLeod
• Tim Moores
• Stephan van Hulst
• Piet Souris
• Ganesh Patekar
Bartenders:
• Frits Walraven
• Carey Brown
• Tim Holloway

# Recursive Tracing

Ranch Hand
Posts: 38
Hello! I am struggling to understand recursive tracing in the follow scenario (code given below). I realize recursion has two cases - a base case, and a recursive case, which recalls the method. For example, given the following code:

Test(3) goes like this:

Test(3) evaluates to ? ---> test(2) evaluates to ? --- test(1) evaluates to 1, so now go back, up the chain.

We were given the following method as a class example, however I don't understand what two recursive calls, stacked on top on one another, behave like.

Upon running this code i know it prints "1, 2, 3, 4, 5" which almost makes sense to me but something is just not quite clicking. To be clear, this is for a class but is not a homework problem, just an example that was in the notes that I do not understand.

Thanks for any help!

Bartender
Posts: 5906
57
• 3
This might help you. Sprinkle in some print statements and include a "level" number to track the nesting of calls.
Output:

Sheriff
Posts: 13517
223
• 1
It might also help to think about recursive cases as "going down the rabbit hole and (eventually) coming back".

That is, when you have two recursive calls "stacked up," as you say, like that the first call just goes as far down the recursion as it will, come back out when it reaches a base state, and completes the recursive call at that level. Then it continues to the second recursive call and does the same thing.

I think your confusion may lie in thinking about when the second recursive call occurs. That's where the different levels of recursion comes in. Carey's suggested adjustments to the code allows you to better see how recursion levels come into play. At the same level of recursion, program execution simply goes the regular sequential order.

 Consider Paul's rocket mass heater.