Making Change – Solution

To solve this month’s Exercise you had to figure out a way to divvy up a dollar amount into the proper number of quarters, dimes, nickels, and pennies. As with many programming puzzles, a number of ways exist to code a solution. Click here to view mine.

In my solution, I chose to whittle down the dollar amount by given chunks. It’s packing a suitcase by starting with the larger items first and then working down to the smaller ones.

I started by creating variables to count each individual coin, plus another variable, coins_input, for the total:

    int coins_input,quarters,dimes,nickels,pennies;

    quarters = dimes = nickels = pennies = 0;
    coins_input = 131;

Each coin variable is initialized to zero at Line 7. The amount of change I need to work with is set at Line 8.

The bulk of the code is a while loop at Line 11. It keeps working as long as the value of coins_input is greater than zero. An if-else structure within the loop chips away individual coin values, largest to smallest:

    while(coins_input)
    {
        if(coins_input > 25)
        {
            quarters++;
            coins_input -= 25;
        }
        else if (coins_input > 10)
        {
            dimes++;
            coins_input -= 10;
        }
        else if (coins_input > 5)
        {
            nickels++;
            coins_input -= 5;
        }
        else
        {
            pennies++;
            coins_input--;
        }
    }

The if-else structure allows for only one action to happen at a time. Each decision, from the top down, deals with a smaller coin value. Quarters come first: If the total coin value is greater than 25, one quarter is removed, the value of quarters is incremented, the value of coins_input is reduced by 25, and then the loop repeats.

When the value of coins_input is less than 25, the else if statement at Line 18 is executed. Those statements pop off dimes. When the value is less than 10, the else if at Line 23 is executed, popping off nickels. Finally come the pennies when the value of coins_input is less than 5.

The printf() statement at Lines 34 through 38 displays the results:

    printf("%2d quarters\n%2d dimes\n%2d nickels\n%2d pennies\n",
            quarters,
            dimes,
            nickels,
            pennies);

The %2d placeholder keeps output to at least two characters wide for each integer. I split the line for each variable to make it more readable.