# Greedy Algorithms PSET1. I wrote this code but at some cases it fails to give the correct output. Can someone please help me.?

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

int main(void)
{
float dollar;

do                                      //Loop to prompt user to type positive value
{
printf("Value of change owned:");
scanf("%f", &dollar);
}
while (dollar < 0);

int cents = round(dollar * 100);       //To convert dollar to cents

printf("Cents owned:%i\n",cents);

int coin= 0;

for (int i = 0; cents >= 25; i++)      //Loop to count number of coins needed
{
coin = 0 + 1;
cents = cents - 25;
}

for (int j = 0; cents >= 10; j++)
{
coin = coin + 1;
cents = cents - 10;
}

for (int k = 0; cents >= 5; k++)
{
coin = coin + 1;
cents = cents - 5;
}
for (int l = 0; cents >= 1; l++)
{
coin = coin + 1;
cents = cents - 1;
}

printf("Coins needed: %i\n",coin);
return 0;
}
``````

A simple oversight error. Look at this code:

``````for (int i = 0; cents >= 25; i++)      //Loop to count number of coins needed
{
coin = 0 + 1;
cents = cents - 25;
}
``````

On each pass through the code, coin is set to 1. This means that any value over 49 cents will be wrong. It's not incremented because of the 0. I believe that you wanted to write `coin = coin + 1;`

Programming note: The usual way to increment a variable would be like this:

``````coin++;
``````

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

• Thanks. It worked but I have one more problem. My program does not reject input when I type in words. Can you please help me out with this too ? ERROR: :( rejects a non-numeric input of "foo" expected program to reject input, but it did not – MerlinMR Jun 11 at 5:36
• That's part of the assignment. You need to at least attempt to write the code to handle that first. – Cliff B Jun 11 at 6:01
• Yeah, I used get_float and it did prompt the user to type again and the program did run successfully. But ain't it part of training library provide by CS50.... So if this problem happens in real life, is there any else way to do it ? – MerlinMR Jun 11 at 16:42
• the get_float and similar functions in the cs50 library are there to handle more complex tasks while you're at these early stages. They will soon fall away as you gain more skills. If you want to see how they execute these functions, you can study the source code for the cs50 library. Do a google search for cs50.c to find the source code. – Cliff B Jun 11 at 17:06