0

I am a beginner and have worked through the greedy algorithm part of PS1 (prompt the user for the amount of change needed, round/convert it to cents, and determine how the change could be dispensed using the smallest number of coins) and have managed to get it to work, but I'm confused as to why my initial code did not work.

I initially used the do/while condition loops for both the input and for each of the four different types of coins (see below, where c is the amount of change and x is the number of coins). While I only had quarters, the output seemed to be correct. However, when I added the condition loops for the other three types of coins, the output was inaccurate (e.g., an input of 0.50 in change would give an output of 5, where it should obviously be 2).

do
{
    c = c - 25;
    x++;
}
while (c >= 25);
do
{
    c = c - 10;
    x++;
}
while (c >= 10);
do
{
    c = c - 5;
    x++;
}
while (c >= 5);
do
{
    c = c - 1;
    x++;
}
while (c >= 1);

Note: the same inaccurate output resulted when I changed the conditions for the dimes, nickels, and pennies to "while (c >= 10 && c < 25)", "while (c >= 5 && c < 10)"...etc.

However, when I used the following formatting of the do/while condition loops, it seemed to work:

while (c >= 25)
{
    c = c - 25;
    x++;
}
while (c >= 10)
{
    c = c - 10;
    x++;
}
while (c >= 5)
{
    c = c - 5;
    x++;
}
while (c >= 1)
{
    c = c - 1;
    x++;
}

I'm sure this is an extremely basic issue, but I'm just confused as to why the first block didn't work, so if anyone can shed any light, it would be much appreciated. Thank you!!

1
  • The problem most likely lies in what is not posted. Is c a float or an int? How was the original value assigned to it? Please edit your question and add the missing code.
    – Cliff B
    Commented Sep 5, 2016 at 20:31

1 Answer 1

1

Do while behaves slightly different than while. You managed to find the exact difference :).

Do while executes the code inside once and then checks your condition.

That means in all cases the Do While will run at least once even if condition is not met. As such you put 0.50 the first Do while(for the 25) runs twice until the condition fails and then the rest of 3 loops each run once and you get 5.

The simple While loop checks the condition first and only if it's valid runs and it checks again at the beginning of each cycle.

In short:

Do while checks condition after the cycle (will always run once)

While checks condition before the cycle.

1
  • Ahhhh. Great - thank you so much! Commented Sep 7, 2016 at 0:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .