There are are several languages that don't support loops (ie. for and while), and as a result when you need repeating behavior, you need to use recursion(I believe that J does not have loops). In many examples, recursion requires much less code. For example, I wrote an isPrime method, it took only two lines of code.
public static boolean isPrime(int n)
{
return n!=1&&isPrime(n,2);
}
public static boolean isPrime(int n,int c)
{
return c==n||n%c!=0&&isPrime(n,c+1);
}
The iterative solution would take much more code:
public static boolean isPrime(int n)
{
if(n==1) return false;
int c=2;
while(c!=n)
{
if(n%c==0) return false;
}
return true;
}
Another good example is when you are working with ListNodes, for example if you would like to check if all the elements in a ListNode are the same, a recursive solution would be much easier.
public static <E> boolean allSame(ListNode<E> list)
{
return list.getNext()==null||list.getValue().equals(list.getNext().getValue())&&allSame(list.getNext());
}
The iterative solution would look something like this:
public static <E> boolean allSame(ListNode<E> list)
{
while(list.getNext()!=null)
{
if(!list.getValue().equals(list)) return false;
list=list.getNext();
}
return true;
}
As you can see, in most cases recursive solutions are shorter than iterative solutions.