It can be proven mathematically that all recursive algorithms have non-recursive counterparts. For instance the factorial method could have been written non-recursively like this:
public static long factorial (int n) { long result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } The non-recursive equivalent in this problem is straight-forward, but sometimes the non-recursive counterpart to a recursive algorithm isn't at all obvious. To see that one always exists, note that at the machine level of the computer, there's no such thing as recursion and that everything consists of values on a stack. Therefore even if you can't find a simpler way to rewrite the algorithm without recursion, you can always use your own stack instead of the Java stack.
Here's an example of a recursive program for which I have not been able to find a simple, non-recursive equivalent method. The goal is to find all possible RAM configurations for a PC, given the size of the memory chips it will accept and the number of slots it has available. We are not concerned with how the RAM is arranged inside the PC, only with the total quantity of installed RAM. For some computers this can easily be calculated by hand. For instance Apple's PowerBook 5300 series comes with 8 megabytes of RAM soldered onto the logic board and one empty slot that can hold chips of 8, 16, 32 or 56 MB capacity. Therefore the possible Ram configurations are 8, 16, 24, 40 and 64 MB. However as the number of available slots and the number of available chip sizes increases this becomes a much more difficult problem. The following is a recursive program to calculate and print all possible RAM configurations:
import java.util.Hashtable; import java.util.Enumeration; public class RamConfig { static int[] sizes = {0, 8, 16, 32, 64}; static Hashtable configs = new Hashtable(64); static int slots[] = new int[4]; public static void main (String args[]) { System.out.println("Available DIMM sizes are: ); for (int i=0; i < sizes.length; i++) System.out.println(sizes[i]); fillSlots(slots.length - 1); System.out.println("Ram configs are: ); for (Enumeration e = configs.elements(); e.hasMoreElements(); ) { System.out.println(e.nextElement()); } } private static void fillSlots(int n) { int total; for (int i=0; i < sizes.length; i++) { slots[n] = sizes[i]; if (n == 0) { total = 0; for (int j = 0; j < slots.length; j++) { total += slots[j]; } configs.put(Integer.toString(total), new Integer(total)); } else { fillSlots(n - 1); } } } }