/* Java class containing several recursive methods that "narrate" their own ** execution, for the purpose of aiding the understanding of how recursion ** works. */ public class RecursionExamples { private static final int DEPTH_INDENT = 3; private static int depth; /* Returns the sum of the integers in the range [low..high]. */ public static int sumOfRange(int low, int high) { int result = 0; depth = depth + 1; println(depth, "Received low: " + low + "; high: " + high); if (low > high) { result = 0; } else { result = low + sumOfRange(low+1, high); } println(depth, "Returning " + result + ", having received " + low + "; high: " + high); depth = depth - 1; return result; } public static void main(String[] args) { depth = -1; sumOfRange(4,8); } // methods for printing messages that appear after an appropriate // indent in accord to the recursive depth of the calling instance. // ---------------------------------------------------------------- /* Prints the given string (s) following an indent indicated by 'depth'. */ private static void print(int depth, String s) { int indent = DEPTH_INDENT * depth; printSpaces(indent); //String format = "%" + indent + "s%s"; System.out.print(s); } /* Prints the given string (s) following an indent indicated by 'depth'; ** then skips to the next line. */ private static void println(int depth, String s) { print(depth, s); System.out.println(); } private static void printSpaces(int num) { for (int i=0; i != num; i++) { System.out.print(' '); } } }