0

I think I am quite far with greedy, but I still have a big problem with my do/while loops. The problem I think is that when the code progresses, it automatically reads all the do/while loops and increment the value of ALL the counts (countquarter,countdime, ...) by 1 at least, resulting in a false result. I have tried different ways but all of them are not convincing. How can I avoid this?
Thanking you guys in advance. Frédéric.

#include <stdio.h>
#include <math.h>
#include <cs50.h>

int main (void)
{

    printf("How much change is owed?\n");

    float change = GetFloat();

    int money = roundf(change * 100);

    int countquarter=0;
    {
        do
        {
            money = money-25;
            countquarter = countquarter + 1;
        }
        while (money >= 25);
    }
    int countdime=0;
    {
        do
        {
            money = money-10;
            countdime = countdime + 1;
        }
        while (money >= 10);
    }
    int countnickel=0;
    {
        do
        {
            money = money-5;
            countnickel = countnickel + 1;
        }
        while (money >= 5);
    }
    int countpenny=0;
    {
        do
        {
            money = money-1;
            countpenny = countpenny + 1;
        }
        while (money >= 1);
    }


    printf("%d\n", countpenny);
    printf("%d\n", countnickel);
    printf("%d\n", countdime);
    printf("%d\n", countquarter);
    int count=(countpenny+countnickel+countdime+countquarter);
    printf("%d\n", count);
}
1

Your analysis is correct. Perhaps you might want to review class materials on the difference between while loops and do/while loops?

A do/while loop is guaranteed to run at lease once because the test is done after the loop executes.

A while loop (which is different from a do/while loop) may not execute the loop at all because the test is done before the loop executes.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

| improve this answer | |

You must log in to answer this question.

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