22222222
22222222

Reputation: 581

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?

Upvotes: 0

Views: 1901

Answers (2)

Richard Schneider
Richard Schneider

Reputation: 35477

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

Upvotes: 0

Ed Staub
Ed Staub

Reputation: 15690

Consider a function that will take a count as an argument, then, if its next to a beeper, increase the count and call itself with the new count. If it's not next to a beeper, it's done. In either case it should return the current count. I might have made this too easy - not sure!

Upvotes: 6

Related Questions