The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. 
Home Conditionals, Graphics and Recursion Stack Diagrams for Recursive Methods  
See also: More Recursion  
Search the VIAS Library  Index  
Stack Diagrams for Recursive Methods
In the previous chapter we used a stack diagram to represent the state of a program during a method call. The same kind of diagram can make it easier to interpret a recursive method. Remember that every time a method gets called it creates a new instance of the method that contains a new version of the method's local variables and parameters. The following figure is a stack diagram for countdown, called with n = 3: There is one instance of main and four instances of countdown, each with a different value for the parameter n. The bottom of the stack, countdown with n=0 is the base case. It does not make a recursive call, so there are no more instances of countdown. The instance of main is empty because main does not have any parameters or local variables. As an exercise, draw a stack diagram for nLines, invoked with the parameter n=4.


Home Conditionals, Graphics and Recursion Stack Diagrams for Recursive Methods 