# CS50 Newbie needs help! Pset 1 cash problem. It compiles and runs but answers are wrong :(

Please check the code below. It runs fine but with a few "errors". when I input 0.41 as per the problem example, it gives me 16 coin count instead of 4. What is missing? Please help me understand. the only thing I really know and understand so far is Line 1 (not shown) until 'int cents'. Thank you so much.

``````    int i = 0; //initialize coin count from 0
int cents = round(change*100);

if (cents >= 25) //condition for coin count if change is greater than or equal to 25
{
cents = cents - 25;
i++;
}
else if (cents >= 10 && cents < 25) //coin count if change is greater than 10 and less than 25
{
cents = cents - 10;
i++;
}
else if (cents >= 5 && cents < 10)
{
cents = cents - 5;
i++;
}
else if (cents >= 1 && cents < 5)
{
cents = cents - 1;
i++;
}
printf("%i\n", cents);
}
}
``````

I'm not sure that your statement about the results is accurate, but no matter. [EDIT: I didn't see that the printed result is the var change, not i (the count of coins.) ]

This code will only count 1 quarter, 1 dime, 1 nickel and 1 penny each, at most.

The problem is that it uses if statements where it should have used while statements.

There may be other issues, but this is the main problem.

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

• i just did "make" again and it complied. Sorry I was not clear in my post, I meant that the number of coins should be 4 instead of 16 (based on the problem set example). ~/pset1/cash/ \$ make cash ~/pset1/cash/ \$ ./cash Change Owed: 0.41 16
– DyRi
Sep 17, 2020 at 21:00
• I missed something. Along with counting incorrectly, the last line prints out cents, not i (the actual coin count). This is one reason why single letter var names shouldn't be used other than loop counters. If i were renamed coins, this error might not have been made. Sep 17, 2020 at 21:12
• oh you're right! I renamed it to 'coins'. so after recompiling it, the number of coins in my result is 3, which is now closer to the intended coin count of 4. since int coins is initialized to 0, it should be counted as one but seems like my code didn't count it.
– DyRi
Sep 17, 2020 at 21:41
• as I said, those if statements should be while statements. IF statements will only count and subtract once for each type of coin. A while loop will repeat until the proper number of quarters (for example) are counted. Sep 17, 2020 at 21:50
• NOW IT WORKED. Thank you for your help and speedy response! :)
– DyRi
Sep 17, 2020 at 21:56