public class RecursiveDemo { private static int depth; public static void main(String[] args) { depth = -1; if (args.length == 1) { int n = Integer.parseInt(args[0]); sumUpTo(n); } else { int m = Integer.parseInt(args[0]); int n = Integer.parseInt(args[1]); sumOfRange(m,n); } } /* Computes the sum of the integers in the range [0..n] using recursion. ** Also narrates its execution. */ public static int sumUpTo(int n) { depth++; printMessage("Received n:" + n); int result; if (n == 0) { result = 0; } else { int sumOfLesser = sumUpTo(n-1); printMessage("Adding n (" + n + ") to " + sumOfLesser); result = sumOfLesser + n; } printMessage(String.format("Having received %d; Returning %d", n, result)); depth--; return result; } /* Computes the sum of the integers in the range [u..v] using recursion. ** Also narrates its execution. */ public static int sumOfRange(int u, int v) { depth++; printMessage(String.format("Received u:%d, v:%d", u, v)); int result; if (u > v) { result = 0; } else { int sumFromVplus1 = sumOfRange(u+1, v); printMessage("Adding u (" + u + ") to " + sumFromVplus1); result = u + sumFromVplus1; } printMessage(String.format("Having received u:%d, v:%d; Returning %d", u, v, result)); depth--; return result; } private static void printMessage(String s) { printSpaces(2*depth); System.out.println(s); } private static void printSpaces(int num) { for (int i=0; i != num; i++) { System.out.print(" "); } } }