[Solved] Recursion doesn’t do what its supposed to be doing


Let’s step through your code

static void Main(string[] args)
    {
        int input = 7;
        int zeroes = 0;

        List<int> myList = ATM(input);

mylist => [3,2,1]

        foreach(var number in myList.ToArray())
        {
            if (number != 0)
            {
                myList.AddRange(ATM(number));
            }
            else
            {
                continue;
            }
  • after 3 mylist => [3,2,1,1,1,0]
  • after 2 mylist => [3,2,1,1,1,0,1,0,0]
  • after 1 mylist => [3,2,1,1,1,0,1,0,0,0,0,0]
        }

count the zeros by hand … and you see 6 zeros

        foreach (var zero in myList)
        {
            if (zero == 0)
            {
                zeroes += 1;
            }
        }

        Console.WriteLine(zeroes);
        Console.ReadKey();


        Console.ReadKey();
    }

    static List<int> ATM(int value)
    {
        List<int> exchangeCoins = new List<int>();

        if (value != 0)
        {                                 // 7 3 2 1
            exchangeCoins.Add(value / 2); // 3 1 1 0
            exchangeCoins.Add(value / 3); // 2 1 0 0
            exchangeCoins.Add(value / 4); // 1 0 0 0
        }
       else
        {
            throw new Exception("Value can't be zero!");
        }

        return exchangeCoins;

    }
}

Thats why your code returns 6


If your goal is to get 15 zeros then you have to design ATM being recursive:

static void Main( string[ ] args )
{
    int input = int.Parse( Console.ReadLine() );
    int zeroes = 0;

    List<int> myList = ATM( input );

    foreach ( var zero in myList )
    {
        if ( zero == 0 )
        {
            zeroes += 1;
        }
    }

    Console.WriteLine( zeroes );
    Console.ReadKey();


    Console.ReadKey();
}

Recursive call in ATM

static List<int> ATM( int value )
{
    List<int> exchangeCoins = new List<int>();

    if ( value != 0 )
    {
        exchangeCoins.Add( value / 2 );
        exchangeCoins.Add( value / 3 );
        exchangeCoins.Add( value / 4 );

        // recursive call on the three items
        foreach ( var item in exchangeCoins.ToArray() )
        {
            exchangeCoins.AddRange( ATM( item ) );
        }
    }

    return exchangeCoins;

}

1

solved Recursion doesn’t do what its supposed to be doing