0

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?

2 Answers 2

6

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!

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.