print all the amounts that can be paid using only n coins - c

I have a homework problem where the user inputs a number of coins N. The program is supposed to find all the amounts you can make if those coins could be made up of any combination of pennies, nickles, dimes, and quarters.
I had read other posts where they recommend so much to us dynamic programming, so I used DP in my program for the solution below:
#include <stdio.h>
#include <stdlib.h>
// q(quater), d (dime), n(nickle), p(penny).
int find_coin(int *q, int *d, int *n, int *p, int k)
{
int count = 0;
*q = k / 25;
count += *q;
k = k % 25;
*d = k / 10;
count += *d;
k = k % 10;
*n = k / 5;
count += *n;
k = k % 5;
*p = k;
count += *p;
return count;
}
int main() {
int q,d,n,p;
int k = 0;
int i = 0;
int counts = 0;
puts("\nEnter a number of coins: ");
scanf("%d", &k);
find_coin(&q, &d, &n, &p, k);
printf("%3d cents:\t", k);
printf("total of pennies: %d ",p);
printf("total of nickles: %d ",n);
printf("total of Dimes: %d ",d);
printf("total of quaters: %d \n",q);
getchar();
}
My output is:
Enter a number of coins:
5
5 cents: total of pennies: 0 total of nickles: 1 total of Dimes: 0 total of quaters: 0
But my professor now asks me for this output:
Enter the number of coins
2
2 cents: 0 quarters 0 dimes 0 nickels 2 pennies
6 cents: 0 quarters 0 dimes 1 nickels 1 pennies
11 cents: 0 quarters 1 dimes 0 nickels 1 pennies
15 cents: 0 quarters 1 dimes 1 nickels 0 pennies
20 cents: 0 quarters 2 dimes 0 nickels 0 pennies
26 cents: 1 quarters 0 dimes 0 nickels 1 pennies
30 cents: 1 quarters 0 dimes 1 nickels 0 pennies
35 cents: 1 quarters 1 dimes 0 nickels 0 pennies
50 cents: 2 quarters 0 dimes 0 nickels 0 pennies
I tried my solution using a loop, but my loop is incorrect. I did something wrong in the code where the loop is just overloading:
for(i = 1; i > counts; i++) {
printf("%3d cents:\t", k);
printf("total of pennies: %d ",p);
printf("total of nickles: %d ",n);
printf("total of Dimes: %d ",d);
printf("total of quaters: %d \n",q);
k++;
}

You've gotten this backwards, and probably became confused by reading solutions to problems whose only similarity was dealing with coins. Look at what this does:
int find_coin(int *q, int *d, int *n, int *p, int k)
That routine takes in an amount k which is value in cents, and gives back a breakdown of the fewest number of coins that could achieve that amount. Then it returns the count of coins. So if you gave it 26 cents as k it would poke 1 into *q, leave *d and *n at zero, and give you *p as 1. One penny and one quarter makes 26 cents--with a return value indicating two total coins. It wouldn't give you *p as 26 to make 26 cents.
(I'll point out that this has nothing to do with the concept whose somewhat-misleading name is "dynamic programming".)
So if the goal of the program was to take in a total currency value and then print out the fewest coins that make it up, your program would be correct. Imagine if the prompt said:
Enter a number of cents:
Then if you input 5 as with your case, the "optimal" answer is a single coin of one nickel. That's what you got. A correct answer to a problem you weren't assigned.
The real problem is about combinations. If I could have two coins and they could be any from the set...I'd want those to be two quarters for a maximum of 50 cents. But the question is what are all the possibilities, without counting possibilities twice. So you only need to mention two pennies once to make 2 cents.
Look at what your prompt actually says:
Enter a number of coins:
A good lesson here is that you should line up your variable names with things in the problem statement. Both the problem statement (and your question title) talk about "n" coins. So why not call your variable either n or coins? When you name things meaningfully mistakes will jump off the page, as in the mismatch that would have been here between cents and coins:
printf("%3d cents:\t", coins);
Adding some haphazard loops onto this isn't going to get you to the right answer. So it's time to go back to the drawing board. You'll be needing essentially the opposite of find_coin...something that takes a number of quarters, dimes, nickels, and pennies and gives you back the amount of money that represents. And some loops and some research on how to produce combinations.
(Note: When I mention that haphazard loops won't get you the answer, I mean it really can't. One might think that if you were asked to do 5 coins you could say the maximum amount of money in cents would be 5 times 25 for five quarters...with the minimum as 5 times 1 for five pennies. Then count from 5 to 125 and print out all the cent tallies where find_coins returned five coins. But can you see why that can't work? find_coins won't find the five pennies case because it is "inefficient", it can only see that as one nickel. But you're asked to find all combinations of the 5 coins, so that's a combination that needs to be found and output.)

Related

issue with a program in c to check a num whether is equally divisible by 2 through 9

I am a beginner in c programming and I tried to write a program that asks for a number from 1 to 100 and tells then which numbers are equally divisible by 2 through 9. the point is I intended to show the result by 1 printf() and I wrote 8 %f and variable but some numbers have just 1 or 2 divisible not 8 !!!
int num;
float a2,a3,a4,a5,a6,a7,a8,a9,n2,n3,n4,n5,n6,n7,n8,n9;
float b2,b3,b4,b5,b6,b7,b8,b9;
printf("please enter an int number between 1 to 100 \n");
scanf(" %d", &num);
a2=( num % 2 == 0)?(b2=2):(n2);
a3=( num % 3 == 0)?(b3=3):(n3);
a4=( num % 4 == 0)?(b4=4):(n4);
a5=( num % 5 == 0)?(b5=5):(n5);
a6=( num % 6 == 0)?(b6=6):(n6);
a7=( num % 7 == 0)?(b7=7):(n7);
a8=( num % 8 == 0)?(b8=8):(n8);
a9=( num % 9 == 0)?(b9=9):(n9);
printf("your chosen number is divisible by %.0f %.0f %.0f %.0f %.0f %.0f %.0f %.0f ",b2,b3,b4,b5,b6,b7,b8,b9);
There are too many problems in your code:
You print the values of all b even if the given number is not divisible by one of [2, 9]
What is the purpose of a and n?
You have not initialized b. It can carry garbage values because of those conditions.
Why do you use floating point variables? Divisibility tests are for integers only.
Solution:
Instead of hardcoding a pattern, simply run a loop, and check and display the result simultaneously.
printf("%d is divisible by:", num);
for (int i = 2; i <= 9; ++i)
{
if (num % i == 0)
{
printf(" %d", i);
}
}
By the way, your code does not check if the given number is in your desired range as well.

C: Unable to use modulus operators to break down change into denominations, storing into an array and print the output to the user

I'm attempting to write a program in which:
The user inputs the cost of an item
The user inputs the amount they paid for the item
The program determines if the user is owed any change
The program calculates the amount of change owed
The program uses the modulus operator to break the amount of change down into coin denominations
The program stores the change and coin denominations into an array This is the first bit at which I'm getting stuck
The program displays the amount of change in coin denominations to the user
The purpose is to use an array to hold the values of the coins, so I "can write a general purpose change calculator that can be used for any coinage by changing the contents of the array".
Here is my code:
void vendingMachine()
{
// Declarations
#define ARRAY_LENGTH 6
int itemCost;
int amountEntered;
int fifty, twenty, ten, five, two, one;
int remainder;
// User input
printf("Please enter the cost of the item in pence: ");
scanf_s("%d", &itemCost);
while (itemCost <= 0 || itemCost > 99)
{
printf("You've entered an invalid amount. Please enter an amount between 1p and 99p: ");
scanf_s("%d", &itemCost);
}
printf("Please enter the amount entered into the machine in pence: ");
scanf_s("%d", &amountEntered);
while (amountEntered <= 0 || amountEntered > 100)
{
printf("You've entered an invalid amount. Please enter an amount between 1p and 100p: ");
scanf_s("%d", &amountEntered);
}
while (amountEntered < itemCost)
{
printf("You've entered an invalid amount. Please enter an amount equal to or higher than the cost of the item: ");
scanf_s("%d", &amountEntered);
}
// Program to determine if the customer is owed any change and, if so, how much is owed
if (amountEntered == itemCost)
{
printf("No change is owed to the customer");
}
else if (amountEntered > itemCost)
{
int change = amountEntered - itemCost;
printf("The amount of change owed to the customer is: %d pence, broken down as follows: \n", change);
fifty = change / 50;
remainder = change % 50;
twenty = remainder / 20;
remainder = remainder % 20;
ten = remainder / 10;
remainder = remainder % 10;
five = remainder / 5;
remainder = remainder % 5;
two = remainder / 2;
remainder = remainder % 2;
one = remainder;
// Program to store the change in an array
int count[ARRAY_LENGTH];
count[0] = fifty;
count[1] = twenty;
count[2] = ten;
count[3] = five;
count[4] = two;
count[5] = one;
for (int i = 0; i < ARRAY_LENGTH; i++)
{
count[i] = 0;
}
for (int i = 0; i < ARRAY_LENGTH; i++)
{
printf("The number of %d coins is: %d\n", //I don't know what to do here);
}
}
}
Store the type of coins in an array as well, e.g.
const int coins[ARRAY_LENGTH] = { 50, 20, 10, 5, 2, 1 };
Then you can easily refer to them in your loop:
printf("The number of %d coins is: %d\n", coins[i], count[i]);
This also allows you to perform your modulo calculations in a loop.
I am not sure what you are trying to achieve here:
The following piece of (your) code sets the values of count from index 0 to index 5, starting from fifty to one..
int count[ARRAY_LENGTH];
count[0] = fifty;
count[1] = twenty;
count[2] = ten;
count[3] = five;
count[4] = two;
count[5] = one;
Then here, you are overwriting those with 0 in the for loop.
for (int i = 0; i < ARRAY_LENGTH; i++)
{
count[i] = 0;
}
So above loop is not required, or at least must not be placed after you have assigned values of fifty, twenty, ten, five, two and one to count array indices.
I guess you are trying to print them? You don't have to use a loop here:
// Doing it the newbie-way:
printf("The number of coins of 50 are: %d\n", count[0]);
printf("The number of coins of 20 are: %d\n", count[1]);
printf("The number of coins of 10 are: %d\n", count[2]);
printf("The number of coins of 5 are: %d\n", count[3]);
printf("The number of coins of 2 are: %d\n", count[4]);
printf("The number of coins of 1 are: %d\n", count[5]);

Getting crazy large numbers, possibly due to improper manipulation of doubles and ints (C language)

I'm writing a program for my CS239 class in C that asks for cost of something, amount paid, calculates tax, and then determines what type of change to return and optimal coins to return.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
void coinage(int c, int q, int d, int n, int p); //change calculation function
int main(void)
{
double price, tax, paid, due, t_back; //used double instead of int for decimal purpose
int c, b, q, d, n, p; //change, bills, quarters, dimes, nickels, pennies
printf("\nProgram Author: PuppyBreath\n");
printf("\nEnter price in dollars: $");
scanf("%lf", &price);
tax = 1.06;
due = price*tax;
printf("Sales tax in Kentucky is 6%, therefore the amount due is $%.2f. \n", due);
printf("Enter amount paid: \n");
scanf("%lf", &paid);
paid = paid*100+0.5;
due = due*100;
c = paid-due;
b = c/100;
t_back = (paid-due)/100-0.01; //used a double rather than an int for increased precision
coinage(c, q, d, n, p); //calls coinage function
printf("Change back:\n");
printf("Total: $%.2f\n", t_back);
if(t_back >= 1)
printf("Ones: %d\n", b);
else
printf("No bills\n");
if(q >= 1)
printf("Quarters: %d\n", q);
else
printf("NO QUARTERS FOR YOU!\n");
if(d >= 1)
printf("Dimes: %d\n", d);
else
printf("NO DIMES FOR YOU!\n");
if(n >= 1)
printf("Nickels: %d\n", n);
else
printf("NO NICKELS FOR YOU!\n");
if(p >= 1)
printf("Pennies: %d\n", p);
else
printf("NO PENNIES FOR YOU!\n");
return 0;
}
void coinage(int change, int quarters, int dimes, int nickels, int pennies)
{
int t_change, t_quarters, t_dimes, t_nickels, t_pennies;
t_change = change%100; //use mod to carry remainders and dividing to find number of each coin
t_quarters = t_change/25.00;
t_change = t_change%25;
t_dimes = t_change/10.00;
t_change = t_change%10;
t_nickels = t_change/5.00;
t_change = t_change%5;
t_pennies = t_change+0.5;
quarters = t_quarters;
dimes = t_dimes;
nickels = t_nickels;
pennies = t_pennies;
}
This is my code, and after I compile it this is what happens: (the '8' and '10' are my inputs)
./a.out
Program Author: PuppyBreath
Enter price in dollars: $8
Sales tax in Kentucky is 6%, therefore the amount due is $8.48.
Enter amount paid:
10
Change back:
Total: $1.51
Ones: 1
NO QUARTERS FOR YOU!
NO DIMES FOR YOU!
Nickels: 4195472
NO PENNIES FOR YOU!
As you know, if your change is $1.51 (supposed to be $1.52 but thats another slightly smaller fish) then you definitely don't need 4,195,472 nickels. Why is this happening? Thanks in advance! I'm not extremely experienced in this, I'm only 3 weeks into any C programming, be gentle!
void coinage(int change, int quarters, int dimes, int nickels, int pennies)
Remember that in C, all arguments are passed by value, thus anything you modify in this function, aren't modified in the out world.
Change it to take pointers to simulate pass-by-reference, the signature should look like this, the body should be modified accordingly.
void coinage(int change, int *quarters, int *dimes, int *nickels, *int pennies)
The core problem here is that the coinage function is designed to return multiple values but the writer has not yet learned good ways of doing so.
One alternative is to redesign the interface so that the coinage function only returns one value, but gets called several times. One could make it take three parameters, the amount of change, the denomination of the current coin, and the denomination of smallest coin with higher value than current. It would return a simple int representing the count for the current coin. The existing coinage function effectively contains this as a block of code that is repeated with only changes in the numbers, not what it is doing.
In the main function variables such as q would be replaced by the expression coins(c, 25, 100), meaning the number of 25 unit coins for change amount c given existence of 100 unit coins or bills.

Why is my loop breaking early?

I am writing a function for class that takes an amount of money and tells the user how many coins add up to that amount. I seem to have everything working just fine, except pennies. My loop will sometimes stop short and break before adding the proper amount. It usually will stop 1 penny short, but sometimes it will give me the proper answer (one value I have found that gives the correct answer is .09). I've tried changing the float to a double, and I have the same issue. I am pulling my hair out trying to figure out what I am doing wrong.
void change(float total)
{
int quarters, dimes, nickels, pennies;
quarters = 0;
dimes = 0;
nickels = 0;
pennies = 0;
printf("\nTotal value entered: %.2f", total);
while (total >= .25)
{
quarters += 1;
total -= .25;
}
while (total >= .10)
{
dimes += 1;
total -= .10;
}
while (total >= .05)
{
nickels += 1;
total -= .05;
}
while (total >= .01)
{
pennies += 1;
total -= .01;
}
printf("\nQuarters: %d \nDimes: %d \nNickels: %d \nPennies: %d\n\n", quarters, dimes, nickels, pennies);
}
It's almost certainly caused by the limited precision of floating point numbers.
You'll probably find that you're reaching a point where the remaining value is something like 0.009999942 rather than 0.1 and that's why you're exiting early.
But it can show itself even before you reach pennies, if you end up with something like 0.249999 left, which should be a quarter but precision limits may force down to two dimes and four pennies.
As to solving it, I'd get the floating point value rounded to an integer as quickly as possible (multiplying it by a hundred beforehand of course), then you don't have to worry about floating point precision.
You can do this with something like:
int itotal = total * 100 + 0.2;
then using itotal for your calculations:
while (itotal >= 25) {
quarters++;
itotal -= 25;
}
// and so on ...
I had a similar question a while back for one of my labs. Instead of a a while loop for each coin denominations, i had a single do..while with cascaded if statements. In my case the max cost of an item was $1, and I opted to work in ints, but you can format the final output later.
int price, remainder, quarters, dime, nickel, pennies;
printf("Enter the price of the item you bought:>");
scanf("%d", &price);
remainder = 100 - price;
do {
if (remainder >= 25)
{
quarters++;
remainder -= 25;
}
else if (remainder >= 10)
{
dime++;
remainder -= 10;
}
else if (remainder >= 5)
{
nickel ++;
remainder -=5;
}
else if (remainder >= 1)
{
pennies ++;
remainder -=1;
}
} while (remainder > 0);
printf("\nYour change will be dispensed as:\n Quarters: %d \n Dimes: %d \n Nickel: %d \n Pennies: %d \n\n", quarters, dime, nickel,pennies);
Hope it helps.
Floating point math is not exact. See http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
Floating point math is very complex and subject to many common mis expectations. Try converting your math to using int, and later translate it back.
As you are comparing float which subjected to be full of errors so you can use a roundof function and change the floating point number to integer.
int_total = round( total * 100.0 ); //include math.h
Now, change the loop as,
while (total >= 25)
{
quarters += 1;
total -= 25;
}

Small bug in my short C code. Why?

I can't figure out why this works for 90% of the inputs, but not the others. It is meant to tell you how many coins you would get back in change. Most test amounts work fine, but if you enter 4.20 (or $4.20), it returns 23 coins... it should be 18 coins (16 quarters and 2 nickels). Where is the bug? Here is my code:
#include <stdio.h>
#include <cs50.h>
int main(void){
float change = 0.00;
printf("How much change is owed? ");
change = GetFloat();
float quarters = change/.25;
change-= (int)quarters*.25;
float dimes = change/.10;
change-= (int)dimes*.10;
float nickels = change/.05;
change-= (int)nickels*.05;
float pennies = (change+.005)/.01;
change-=(int)pennies*.01;
int total = (int)quarters+(int)dimes+(int)nickels+(int)pennies;
printf("%d\n", total);
return 0;
}
The closest float value to 4.20 is slightly smaller than that (4.19999980926513671875, for the usual 32-bit IEEE754 floats). So after you subtracted the $4 from the 16 quarters, you have an amount left that is slightly smaller than 0.2. Dividing that by 0.1 results in a value slightly smaller than 2, so your nickels value is 1. The same happens then after you subtract your nickel, the value is slightly smaller than 0.1, dividing by 0.05 results in a quotient slightly smaller than 2.
You should use integers only for such a computation, calculating in cents.
Throw out the floating-point calculations. this is all based on hundredths at best, so just use integer division/modulo. Never rely on perfect accuracy in floating point numbers.
#include <stdio.h>
#include <cs50.h>
int main(void){
float fchange = 0.00;
int change = 0;
printf("How much change is owed? ");
fchange = GetFloat();
change = (int)roundf(fchange*100.0);
int quarters = change/25;
change = change % 25;
int dimes = change/10;
change = change % 10;
int nickels = change/5;
change = change % 5;
printf("%d quarters, %d dimes, %d nickels, %d pennies\n", quarters, dimes, nickels, change);
return 0;
}
The other answers have it mostly covered: you should be working with fixed point here, not floating point. Be careful to round properly when going from the floating point input to your fixed point representation, though. Here is a short version I hacked up, which should work for all positive inputs:
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char ** argv)
{
float change = atof(argv[1]);
int work = (int)(100*change+0.5);
int quarters, dimes, nickels, pennies;
quarters = work/25; work %= 25;
dimes = work/10; work %= 10;
nickels = work/5; work %= 5;
pennies = work;
printf("%.2f dollars = %d quarters, %d dimes, %d nickels and %d pennies: %d coins total\n",
change, quarters, dimes, nickels, pennies, quarters+dimes+nickels+pennies);
return 0;
}
For example:
./change 4.20
4.20 dollars = 16 quarters, 2 dimes, 0 nickels and 0 pennies: 18 coins total

Resources