making greedy algorithm work for every input - c

I wrote a code for greedy algorithm of cs50. It works for inputs between 0 and 1. How can I make it work to inputs like 4.2 , 6.5 , 8 etc?. I have listed my code below. What should I modify in the program?
#include<stdio.h>
#include<cs50.h>
#include<math.h>
int main()
{
int count , change;
float cents;
printf("Enter the change amount : ");
cents = GetFloat();
cents = cents * 100;
change = round(cents);
count = 0;
while(cents < 0 )
{
printf("Enter a positive number : ");
cents = GetFloat();
}
while (change >= 25)
{
change = change - 25;
count++;
}
while (change < 25 & change >= 10)
{
change = change - 10;
count++;
}
while (change < 10 & change >= 5)
{
change = change - 5;
count++;
}
while (change < 5 & change >= 1)
{
change = change - 1;
count++;
}
printf("Total number of coins used : " );
printf (" %d " , count );
printf("\n");
}

I believe that your problem is that you are using bitwise logical operators. You should use && in your comparisons to compare the values of two expressions. There are other little issues: The loop that guarantees positive input should multiply cents by 100 and round(), before assigning this new value to change. But you don't actually need both change and cents. And you don't need as many comparisons as you have written, and without the extra comparisons, you don't need the logical operators that were causing you trouble in the first place!
Edit
I noticed that a number like 4.20 was being rounded first, then multiplied by 100! Of course this is wrong, giving the same results for 4.20, 4.75, and 4. I changed the code below accordingly, but your original code was doing this part correctly (except in the input validation loop, as mentioned earlier). Now the program correctly handle such inputs.
Here is a cleaned-up version (I don't have the cs50.h library, so there are some small differences):
#include <stdio.h>
#include <math.h>
int main(void)
{
int count;
float cents;
printf("Enter the change amount: ");
scanf("%f", &cents);
cents = (float)round(cents * 100);
count = 0;
while (cents < 0) {
printf("Enter a positive number: ");
cents = (float)round(cents * 100);
}
while (cents >= 25) {
cents -= 25;
count++;
}
while (cents >= 10) {
cents -= 10;
count++;
}
while (cents >= 5) {
cents -= 5;
count++;
}
while (cents >= 1) {
cents -= 1;
count++;
}
printf("Total number of coins used: %d\n", count);
return 0;
}

Related

CS50 Problem Set 1(Cash/Greedy algorithm) getting runtime error: signed integer overflow

#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
int count = 0;
float change;
// prompt the user for input
do
{
change = get_float("Change owed: ");
}
while (change <= 0);
int cents = round(change * 100);
while (change >= 25)
{
cents -= 25;
count ++;
}
while (change >= 10)
{
cents -= 10;
count ++;
}
while (change >= 5)
{
cents -= 5;
count ++;
}
while (change >= 1)
{
cents -= 1;
count ++;
}
printf("%i\n", count);
}
If a delete the "round" function and then replace coins with 0.25 0.10 etc. The program works, but it shows the wrong answer on some inputs.
I can't think of anything. I'm new to programming but I feel like this is really simple it's just my lack of intelligence.
Oh my gah. Can I swear here?? I'm so dumb!! The solution was simple! The problem was: I created an integer "cents" which rounds the "change" value. But in every while loop for each cent type I wrote like (change >= 10) when it should've been (cents >= 10) so the rounding actually happens. Now it works just as intended! Here's the corrected(and a little bit changed) code if somebody need help on this problem set:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
float change;
int count = 0;
int total;
// prompt the user for input
do
{
change = get_float("Change owed: ");
}
while (change <= 0); // ask the user for only positive numbers
//rounds the input and stores the value in the variable "total"
total = round(change * 100);
//loops for each type of coins
while (total >= 25)
{
total -= 25;
count ++;
}
while (total >= 10)
{
total -= 10;
count ++;
}
while (total >= 5)
{
total -= 5;
count ++;
}
while (total >= 1)
{
total -= 1;
count ++;
}
//prints the converted(to int) and rounded value
printf("%i\n", count);
}

write a program that will accept an integer value in the range of 5-95 and as a multiple of 5

Im a complete newbie in programming.
I've been instructed to write the program above in the title.
I'm here seeking help from everyone to help me understand and code better.
Can anyone tell me what is wrong with my code? i cant get it to exit the loop
more detailed information on the program:
You are asked to write a simple C program that will accept an integer value in the range
of 5-95 and as a multiple of 5 representing the number of cents to give to a customer in
their change. The program should calculate how many coins of each denomination and
display this to the user. Valid coin values are 50, 20, 10 and 5. Your solution (program
and algorithm) should be modular in nature.
/*This program acts as a coin changer that helps to provide
change user their changes in the highest amount.
*/
#include <stdio.h>
// Delcaration of functions
int coins(int fifty, int twenty, int ten, int five);
int main()
{
// Declare and initialize working storage
int fifty = 0;
int twenty = 0;
int ten = 0;
int five = 0;
int user_input = 0;
int counter = 3;
int coins(int fifty, int twenty, int ten, int five);
// Prompt user for input, prints, and loops for 3 attempts
while (counter > 0)
{
printf("\nPlease enter an amount within the range of 5 to 95\n");
printf("\nPlease enter the amount you wish to change: \n\n");
scanf("%d", &user_input);
if ((user_input < 5) || (user_input > 95))
{
printf("\nInvalid input\n");
printf("\nNumber of attemps: %d\n\n\n\n", counter);
}
counter--;
}
printf("\nYou have exceeded the number of attempts\n");
// Compute number of coins to be given
fifty = user_input / 50;
twenty = user_input / 20;
ten = user_input / 10;
five = user_input / 5;
if (fifty >= 1)
{
printf("\nNumber of fifty cent coins are: %d\n", fifty);
}
else if (twenty >= 1)
{
printf("\nNumber of twenty cent coins are: %d\n", twenty);
}
else if (ten >= 1)
{
printf("\number of ten cent coins are: %d\n", ten);
}
else if (five >= 1)
{
printf("\nNumber of five cent coins are: %d\n", five);
}
return 0;
}
Here is a program that does what you ask. This program could still be improved vastly.
#include <stdio.h>
// Delcaration of functions
int coinReturn(int coinSize, int value)
{
int tmp = 0;
while(value >= coinSize)
{
value-=coinSize;
tmp++;
}
printf("Number of %i cent coins are: %d\n", coinSize,tmp);
return value;
}
int main()
{
// Declare and initialize working storage
int user_input = 0;
int remainingValue;
// Prompt user for input, prints, and loops for 3 attempts
while (1)
{
printf("\nPlease enter an amount within the range of 5 to 95\n");
printf("\nPlease enter a multiple of 5\n");
printf("\nPlease enter the amount you wish to change: \n");
scanf("%d", &user_input);
if ( (user_input < 5 || user_input > 95) || (user_input % 5 != 0))
{
printf("\nInvalid input!\n");
}
else
{
break;
}
}
//Calculate and Print Output
remainingValue = coinReturn(50,user_input);
remainingValue = coinReturn(20,remainingValue);
remainingValue = coinReturn(10,remainingValue);
remainingValue = coinReturn(5,remainingValue);
return 0;
}
I would focus on a couple things if I were you and make sure I learned the concept. These are:
- Break Statements
- Function Declarations and function Definitions
- Modulo
- Flowcharting
This problem can be slightly tricky and flowcharting it when you start is your best bet.

IF condition not working as expected - C Language

I have the below code in which the if condition does not seem to be working as expected.
as an example, if I enter 0.29 the results that are given are
Quarters: 1
Dimes: 0
Nickels: 4205264
Pennies: 4
As you can see this is incorrect as after the first if statement is performed 'if (cents >= 25)' this would leave a remainder of 4 which is stored in the 'cents' variable. This should mean that the next two 'IF' statements return a '0' and the final if statement is carried out 'if (cents >= 1)'. This is however not the case as you can see that Nickles is returning a value of 4205264.
When you enter 1.17 the result returns as expected:
Quarters: 4
Dimes: 1
Nickels: 1
Pennies: 2
#include <cs50.h>
#include <math.h>
#include <stdio.h>
int main(void)
{
float dollars;
int cents;
int quartersUsed;
int dimesUsed;
int nickelsUsed;
int penniesUsed;
do
{
dollars = get_float("Float: ");
while (dollars <= 0) {
dollars = get_float("Float: ");
}
cents = roundf(dollars * 100);
printf("%i\n", cents);
if (cents >= 25) {
quartersUsed= cents / 25;
cents = cents % 25;
}
if (cents >= 10) {
dimesUsed = cents / 10;
cents = cents % 10;
}
if (cents >= 5) {
nickelsUsed = cents / 5;
cents = cents % 5;
}
if (cents >= 1) {
penniesUsed = cents / 1;
cents = cents % 1;
}
printf("Quarters: %i\n",quartersUsed);
printf("Dimes: %i\n",dimesUsed);
printf("Nickels: %i\n",nickelsUsed);
printf("Pennies: %i\n",penniesUsed);
}
while (dollars == false);
}
You need to initialize your variables, because if you don't enter in a if block, what is happening in your example, you end printing a variable that has been never intialized.
In C, no intialization is done for you so if you don't put a value in your variable, they will have an undefined value (depending on which value was there previously in memory).
Note that your if clauses not only are unnecessary, as they also may let some of your variables to be printed uninitialized (which is probably what is causing the problem in your output). And just as you don't need all those condition checks, you don't need all those variables. Remember that C programmers tend to focus on the economy of operations and space whenever possible. Check my implementation below, compare it to yours, and try to guess how many operations and space it saves. (Since you didn't post your "cs59.h" library, I commented it and implemented a "get_float" function that always returns "1.17".)
#include <stdio.h>
#include <math.h>
//#include <cs50.h>
float get_float(const char *)
{
return 1.17;
}
int main()
{
float dollars;
while((dollars = get_float("Float: ")) <= 0);
int cents = (int) roundf(dollars * 100);
printf("%i\n", cents);
printf("Quarters: %i\n", cents / 25);
printf("Dimes: %i\n", (cents = cents % 25) / 10);
printf("Nickels: %i\n", (cents = cents % 10) / 5);
printf("Pennies: %i\n", cents % 5);
return 0;
}

Confused with why code not running correctly

**I've done a few changes and i'd just like to know if you can help me find out why it isn't running. When I run it the text is printed but the input never stops running. **
The program is meant to replicate(?) the greedy algorithm. It first asks the user how much change is owed and then provides the minimum number of coins with which said change can be made.
I'd greatly appreciate any help you can give with my code.
#include <stdio.h>
#include <math.h>
int main(void)
{
//declared variables
float change;
int num = 0;
// prompts for amount owed
printf("Please provide the amount owed: ");
change = GetFloat();
while (change != 0)
change = change * 100;
int owed = round(change);
{
// if statements for calculating number of coins required
if (owed >= 25)
{
owed = owed - 25;
num ++;
}
if (owed >= 10 && owed < 25)
{
owed = owed - 10;
num ++;
}
if (owed >= 5 && owed < 10)
{
owed = owed - 5;
num ++;
}
if (owed >= 1 && owed < 5)
{
owed = owed - 1;
num ++;
}
}
printf("%d\n", num);
}
When I alter the while statement and comment out the 'change = change * 100;'
it starts to work. However, in doing so the round function won't execute.
change = GetFloat() * 100;
while (change != 0)
// change = change * 1000;
// int owed = round(change);
To my understanding, the part
while (change != 0)
change = change * 100;
is an infinite loop if it is started when change is nonzero. Depending on the platform, eventually NaN or positive infinity is reached by the multiplication, causing the loop to continue forever.

Need to return a value from a do/while and multiple while loops - C

I am trying to build a simple change calculator of sorts. The user inputs an amount of change owed, and then they press return. The value they entered is supposed to be multiplied by 100 first (so that when we round it, the digits are not truncated). The rounding is supposed to turn the float into an int, and then all the math operations (the while loops) should execute, with a single number printing out at end that represents how many coins they were given (i.e. how many quarters, dimes, etc...) The code compiles fine, it prompts the user to input a value, but then when you press return, nothing is executed, and the command line goes back to being blank.
Any ideas what I'm doing wrong? My guess is the values in the while loops are not getting transferred out of the loop, so they can be used in the next loop. But then I am a very early beginner in C language, and not sure the correct rules for the loops. I tried looking up while loop examples, but nothing really explains exactly how to get a value to carry from one while loop to another. If, in fact, that is the problem. Thanks for your help.
CODE REVISION:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main (void) {
float change;
int cents;
int quarter_count = 0;
int dime_count = 0;
int nickel_count = 0;
int pennies = 0;
int total_count;
do
{
printf("Enter the amount of change you are owed: ");
change = GetFloat();
cents = round(change * 100);
}
while (change < 0);
return cents;
int quarter = 25;
while (cents >= quarter)
{
cents = cents - quarter;
quarter_count++;
}
return cents;
int dime = 10;
while (cents >= dime)
{
cents = cents - dime;
dime_count++;
}
return cents;
int nickel = 5;
while (cents >= nickel)
{
pennies = cents - nickel;
nickel_count++;
}
return pennies;
total_count = quarter_count + dime_count + nickel_count + pennies;
printf("%d\n", total_count);
}
After every while loop you put return statement so. Code after first while..loop meaning less.
Also for third while..loop you put condition like while (cents >= nickel) but in while loop you dont alter value of cents.So it will in infinine loop if cent value remain greater then when it reach upto third while..loop.
See my updated code.It will do basic functionality which may be you want
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main (void) {
float change;
int cents;
int quarter_count = 0;
int dime_count = 0;
int nickel_count = 0;
int pennies = 0;
int total_count;
do
{
printf("Enter the amount of change you are owed: ");
change = GetFloat();
cents = round(change * 100);
}
while (change < 0);
int quarter = 25;
while (cents >= quarter)
{
cents = cents - quarter;
quarter_count++;
}
if (cents <= 0)
goto done;
int dime = 10;
while (cents >= dime)
{
cents = cents - dime;
dime_count++;
}
if (cents <= 0)
goto done;
int nickel = 5;
pennies=cents;
while (pennies >= nickel)
{
pennies = pennies - nickel;
nickel_count++;
}
done:
total_count = quarter_count + dime_count + nickel_count + pennies;
printf("%d\n", total_count);
return 0;
}

Resources