Search code examples
javarecursionkarel

How to convert an iterative method into a recursive method (Java)


I am working through a Java course on my own, but I don't have answers to any of the problems. This problem from unit one, based on Karel++, stumped me. There is a robot object on a pile of "beepers" and it needs to determine how many are in the pile and return that value. I need to convert the following iterative method into a recursive method.

public int numOfBeepersInPile()
{
    int count = 0;
    while(nextToABeeper())
    {
        pickBeeper();
        count++;
    }
    return count;
}

Can anyone give me a hint?


Solution

  •  public int numOfBeepersInPile()
     {
         if (nextToBeeper())
         {
            pickBeeper();
            return 1 + numOfBeepersInPile();
         }
         return 0;
     }