Recursive function returning an invalid value in C #

I am trying to understand a set of problems 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 the change to the user giving him the smallest possible number of coins, the available coins are 25, 10, 5 and 1, so in this case there return valueshould be 4 . I used breakpoints and everything works fine until the last minute, when the counter returns a value from 4 to 1.

Let me say again that I can easily solve this problem using a loop, but my goal is to better understand recursion. Any suggestion is helpful, thanks for your time.

+4
1

numberOfCoins, . . counter:

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;
}
+3

Source: https://habr.com/ru/post/1686694/


All Articles