/* Purpose: This program illustrates recursive invocations and the stacking of those invocations. It includes the definition and use of a simple recursive method that just produces illustrative output. Record of revisions: Date Programmer Description of change ==== ========== ===================== March 2003 J. Rodger Original coding May 2003 J. Rodger hsa I/O, user input for depth */ // The "ShowRecursion" class. import hsa.*; public class ShowRecursion { // static (global) variable to keep track of calls public static int stack = 0; // stack depth // helper to show stack growth, shrinkage public static void tabOver (int n) { for (int i = 0 ; i < n ; i++) Stdout.print (" "); } // tabOver // method that does nothing but illustrate stacking // of recursive invocations // uses global variable to track stack depth public static void stacker (int n) { stack++; // print stack depth increasing tabOver (stack); Stdout.print ("Stack depth:" + stack); if (n == 0) { Stdout.println (", n=0, base case, recursion ends"); } else { Stdout.println (", n=" + n + " recurse with n=" + (n - 1)); stacker (n - 1); } // print stack depth decreasing tabOver (stack); Stdout.print ("Stack depth:" + stack); Stdout.println (", invocation with n=" + n + " terminates"); stack--; } // end stacker public static void main (String [] args) { int x; // positive integer for stack illustration Stdout.print ("Enter small positive integer for recursive stack depth:"); x = Stdin.readInt (); Stdout.println ("Simple illustration of recursive stack for x:" + x); stacker (x); Stdout.println ("Recursion ends, back to main method."); } // main method } // ShowRecursion class