2

I am trying to figure some problem set using recursion but every time my return value is 1.

Here is my function

static int numberOfCoins(int n, int counter)
{
    if (n >= 25)
    {
        counter++;
        numberOfCoins(n - 25,counter);
    }
    else if (n >= 10)
    {
        counter++;
        numberOfCoins(n - 10,counter);
    }
    else if (n >= 5)
    {
        counter++;
        numberOfCoins(n - 5, counter);
    }
    else if (n > 0)
    {
        counter++;
        numberOfCoins(n - 1, counter);
    }

    return counter;
}

And here is my call

int returnValue = numberOfCoins(32, 0);
Console.WriteLine("counter: " + returnValue);

The goal is to return change to user giving him smallest possible number of coins, available coins are 25, 10, 5 and 1, so in this case return value should be 4. I've used breakpoints and all works fine until last minute where counter turns value from 4 to 1.

Let me say again, i can easily solve this problem using loop, but my goal is to understand recursion better. Any suggestion is helpful, thank you for your time.

1
  • 4
    Hint: none of your recursive calls do anything useful, given that you're not using the return value from them. You're doing a bunch of work, but then ignoring the result. Commented Sep 30, 2017 at 20:59

1 Answer 1

3

When you call numberOfCoins you just discard the return value. Instead, you should use it and add it to the current count. This will also allow you to remove the counter parameter:

static int numberOfCoins(int n)
{
    if (n >= 25)
    {
        return 1 + numberOfCoins(n - 25);
    }
    else if (n >= 10)
    {
        return 1 +  numberOfCoins(n - 10);
    }
    else if (n >= 5)
    {
        return 1 +  numberOfCoins(n - 5);
    }
    else if (n > 0)
    {
        return 1 + numberOfCoins(n - 1);
    }

    return 0;
}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you, it's like i was blind to the fact that my function returns value every time i call it

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.