I have an assignment that asks us to code an automatic change program for a dollar input up to $200.00. Basically, someone inputs an amount and the output displays that amount in change for the various following denominations (how many 20s, 10s, 5s, 1s, quarters, dimes, nickels, and pennies).
I've worked out a way to do this with if/else statements for each denomination (see below), but I was wondering if there was an easier, more condensed way to execute this with loops? (it's an intro course, so we're not yet at functions/arrays, etc.)
int twenties; int tens;
int fives;
int ones;
int quarter;
int dime;
int nickel;
int penny;
double dollar_ent;
printf("Please enter a dollar amount up to 100: ");
scanf("%lf", &dollar_ent);
printf("Name - Assignment 2 - Change-O-Matic\n\n");
printf("Amount entered: $%.2lf\n\n", dollar_ent);
twenties = (dollar_ent / 20);
if (twenties >=2)
printf("%.0d\t$20.00's\n", twenties);
if (twenties == 1)
printf("%.0d\t$20.00\n", twenties);
else
printf("");
Thanks!
it’ll be easier for you to convert amount into cents.
then you’ll have an integer like 20000 ($200).
have an array of all possible denominations :
int denominations[] = { 2000, 1000, 500, 100, 25, 10, 5, 1}.
then iterate through this array.
divide current amount by current denomination and subtract it from current sum. Compute rest of the division and set it as current sum, then move to next denomination … and so on...
Yes, it is easier to do with a loop. But you'll need an array to go with it:
#include <stdio.h>
static int denoms[] = {
2000,
1000,
500,
100,
25,
10,
5,
1,
0
};
int main () {
double dollar_ent;
int i;
int twenties;
printf("Please enter a dollar amount up to 100: ");
scanf("%lf", &dollar_ent);
printf("Name - Assignment 2 - Change-O-Matic\n\n");
printf("Amount entered: $%.2lf\n\n", dollar_ent);
dollar_ent *= 100;
for(i = 0; denoms[i]; i++) {
twenties = (dollar_ent / denoms[i]);
if (twenties >=2)
printf("%.0d\t$%.02f's\n", twenties, denoms[i] / 100.);
if (twenties == 1)
printf("%.0d\t$%.02f\n", twenties, denoms[i] / 100.);
dollar_ent -= twenties * denoms[i];
}
}
The lesson is this: if you have a program that looks like this:
some code with one value;
similar code with another value;
similar code with yet another value;
Consider replacing it with a loop:
for ( some expression that takes on each value in turn ) {
the identical code, with the values replaced by variables;
}
Not as you have written it. But as you've written it it only finds the number of 20s.
Related
My aim with this program is to tell how many coins of each denomination should be given to a customer with the assumption of inputs being from 5-95.
I have written my program in the best modular form I can, and it seems to be working. However, the program shows 0 for each denomination.
What is the problem?
void PrintDisplay(void)
{
printf("Enter an amount to calculate change: ");
return;
}
int GetChange(void)
{
int change;
scanf("%d%*c", &change);
return(change);
}
int GetCoins(int cents, int coin)
{
int quantity;
quantity = cents / coin;
return(quantity);
}
int GetNewChange(int cents, int coin)
{
int newchange;
newchange = cents - coin;
return(newchange);
}
void PrintResult(int fifties, int twenties, int tens, int fives)
{
printf("The amount of each coin denomination you should give are: \n");
printf("Fifty cent coins: %d \n", fifties);
printf("Twenty cent coins: %d \n", twenties);
printf("Ten cent coins: %d \n", tens);
printf("Five cent coins: %d \n", fives);
return;
}
int main(int input)
{
int FiftyCentAmount;
int TwentyCentAmount;
int TenCentAmount;
int FiveCentAmount;
PrintDisplay();
GetChange();
FiftyCentAmount = GetCoins(input, 50);
GetNewChange(input, 50);
TwentyCentAmount = GetCoins(input, 20);
GetNewChange(input, 20);
TenCentAmount = GetCoins(input, 10);
GetNewChange(input, 10);
FiveCentAmount = GetCoins(input, 5);
GetNewChange(input, 5);
PrintResult(FiftyCentAmount, TwentyCentAmount, TenCentAmount, FiveCentAmount);
system("pause");
return(0);
}
A function has an input (the parameters), an output (return value and maybe parameters passed by pointer) and an algorithm that generates the output from the input.
Sometimes function do not really have an input or output like your superflous PrintDisplay. This is generally okay if you make your code more readable/ better organized that way. Your function is superflous because you make a function (which has four lines) for a simple one line statement. Not inherently bad but superflous.
The return value "appears" at the position where the function call was made. So if you do
input = GetChange();
input will be set to the return value of GetChange.
You fixed this after Daves answer, but didn't see that all your Get... functions also have a return value you just ignore in your code.
So by fixing all of them your code should work (or not see edit).
All your functions (except PrintResult and the textinput) are basically oneliners. And
They reduce to
int GetCoins(int cents, int coin)
{
return cents / coin;
}
int GetNewChange(int cents, int coin)
{
return cents - coin;
}
So an improved program (in your design) would look like this then:
int main()
{
int leftover_change;
printf("Enter an amount to calculate change: ");
leftover_change= GetChange();
int FiftyCentAmount = GetCoins(leftover_change, 50);
leftover_change = GetNewChange(leftover_change, 50);
int TwentyCentAmount = GetCoins(leftover_change, 20);
leftover_change = GetNewChange(leftover_change, 20);
int TenCentAmount = GetCoins(leftover_change, 10);
leftover_change = GetNewChange(leftover_change, 10);
int FiveCentAmount = GetCoins(leftover_change, 5);
leftover_change = GetNewChange(leftover_change, 5);
PrintResult(FiftyCentAmount, TwentyCentAmount, TenCentAmount, FiveCentAmount);
if(leftover_change >0)
{
printf("there are %d cents left\n", leftover_change);
}
system("pause");
return 0;
}
This still vioaltes the DRY concept (Dont repeat yourself) you could fix this (at least partially) by replacing the magic numbers with defines or const variables.
Even better would be a loop that iterates through the different coins. But this needs a bit more thinking and the use of arrays.
edit: I did not check the algorithm in the first place, and my scanfreduction was bullshit but I was in a hurry so here a version that works. To make this answer complete, but as Dave said you should check your algorithm before you implement it.
int GetNewChange(int cents, int coin)
{
return cents % coin; //this is the modulus operator
}
GetChange() returns the user's input, but you aren't saving the result of the call. You want
input = GetChange();
I'm trying to write a code for a bill changer where the amount of money inserted are converted back into coins for the user. The problem is I keep having decimals in my amount of 50c like 222.222 when i input 111.111. My 20c and 10c is unused.. Please help
#include <stdio.h>
int main()
{
double sum50c=0, sum20c=0, sum10c=0, remainder, remainder2, remainder3, end=0;
double amount;
do
{
printf("Please enter an amount(dollars):");
scanf("%lf", &amount);
amount=amount*100;
if(amount<0){
printf("Invalid Input\n");
printf("Re-enter your amount:");
scanf("%lf", &amount);
}
if(amount>=50){
remainder=amount/50;
sum50c=remainder;
}else
if(remainder!=0){
remainder2=remainder/20;
sum20c=remainder2;
}else
if(remainder2!=0){
remainder3=remainder3/10;
sum10c=remainder3;
}
if(sum50c>200||sum20c>200||sum10c>200){
end++;
}else{
end=0;
}
}
while(end<=0);
printf("The amount of 50cents=%lf, 20cents=%lf, 10cents=%lf", sum50c, sum20c, sum10c);
}
There are basically two errors in your code:
Don't operate on floating-point numbers here. The number of coins will be a discrete number, which should be represented as int or maybe even unsigned int. The amount itself may be read in as floating-point number for simplicity, but it should also be converted to the number of cents as integerin order to avoid rounding errors.
You have to find combinations of coins: 30c is 1%times;20c + 1×10c. That means that you can't use else if chains, which will only consider one type of coin. Treat all types of coin, highes denomination first, and then reduce the amount still to handle. Note that with 10c as smallest coin, you might not be able to give full change for all amounts.
Here's you example without the outer loop and without the strange end business:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int num50c = 0,
num20c = 0,
num10c = 0;
int amount; // amount in cents
double iamount; // input amount in dollars
printf("Please enter an amount: ");
scanf("%lf", &iamount);
amount = iamount * 100 + 0.5;
if (amount < 0) {
printf("Invalid Input\n");
exit(1);
}
num50c = amount / 50;
amount %= 50;
num20c = amount / 20;
amount %= 20;
num10c = amount / 10;
amount %= 10;
printf("%d x 50c = %d\n", num50c, num50c * 50);
printf("%d x 20c = %d\n", num20c, num20c * 20);
printf("%d x 10c = %d\n", num10c, num10c * 10);
printf("Remainder: %dc\n", amount);
return 0;
}
To force amount to have integer values you should round the value after your division:
if(amount>=50)
{
remainder=round(amount/50);
sum50c=remainder;
}
I am teaching myself C for fun. I looked online for some practice programs, and found one where you take two input's: One with the amount of an imaginary product, and second the amount of money the imaginary customers gives you. Then you return the number of dollars bills, and change you would give to the customer.
This is the complete code which I wrote to solve this problem:
#include <stdio.h>
#include <stdlib.h>
float getDif(float c, float m)
{
// First find the difference between
// c & m (m - c = d)
float dif = m - c;
// Return the difference
return dif;
}
void getChange(float dif, int* cash, float* change)
{
// If difference is less than 0 we have a problem
// because the customer gave us less money than
// the cost of the product
if(dif < 0)
{
fprintf(stderr, "The customer has not given enough money!...\n");
exit(EXIT_FAILURE);
}
// Cash is seen as the difference without any
// decimals. So if the difference is $13.45
// the cash would be 13 since cash is, in my
// mind paper money
*cash = (int) dif;
// Change is seen as the difference - cash
// if the difference is $13.45 the change
// would be .45
*change = dif - *cash;
}
void getCash(int cash, int* oneHundred, int* fifty, int* twenty, int* ten,
int* five, int* one)
{
if(cash == 0)
{
printf("Wow close to exact change! - No need for cash...\n");
// End the function there is no need to continue
return;
}
// Since cash is > 0 we need to determine the bills to return
// to the user
if(cash >= 100)
{
while(cash >= 100)
{
cash = cash - 100;
(void) ++*oneHundred;
}
}
if(cash >= 50)
{
while(cash >= 50)
{
cash = cash - 50;
(void) ++*fifty;
}
}
if(cash >= 20)
{
while(cash >= 20)
{
cash = cash - 20;
(void) ++*twenty;
}
}
if(cash >= 10)
{
while(cash >= 10)
{
cash = cash - 10;
(void) ++*ten;
}
}
if(cash >= 5)
{
while(cash >= 5)
{
cash = cash - 5;
(void) ++*five;
}
}
if(cash >= 1)
{
while(cash >= 1)
{
cash = cash - 1;
(void) ++*one;
}
}
printf("After all loops cash = %d\n", cash);
}
void getCoins(float change, int* quarter, int* dime, int* nickel, int* penny)
{
// To find the correct change we need to turn the
// current format of variable change (0.57) into
// a easier to work with 57.
int tenChange = change * 100;
if(tenChange >= 25)
{
while(tenChange >= 25)
{
tenChange = tenChange - 25;
(void) ++*quarter;
}
}
if(tenChange >= 10)
{
while(tenChange >= 10)
{
tenChange = tenChange - 10;
(void) ++*dime;
}
}
if(tenChange >= 5)
{
while(tenChange >= 5)
{
tenChange = tenChange - 5;
(void) ++*nickel;
}
}
if(tenChange >= 1)
{
while(tenChange >= 1)
{
tenChange = tenChange - 1;
(void) ++*penny;
}
}
printf("After all loops change = %d\n", tenChange);
}
int main(void)
{
// Create variables for the various things we create
float c, m, dif, change;
int cash, oneHundred, fifty, twenty, ten, five, one, quarter, dime, nickel,
penny;
printf("Enter the exact amount of the items (18.37): ");
// Obtain the cost
scanf("%f", &c);
printf("Enter the amount of money given by the customer: ");
// Obtain the money from customer
scanf("%f", &m);
// Obtain the difference of the cost
// And the money given by calling the
// getDif() function
dif = getDif(c,m);
// Send the difference to the getChange()
// function, as well as the pointers
// cash & change which will be used in the
// function and returned back here
getChange(dif, &cash, &change);
// First send the cash variable to the getCash
// function along with pointers for each bill
// The function will calculate the number of bills
// to give to the customer and return each
getCash(cash, &oneHundred, &fifty, &twenty, &ten, &five, &one);
// Print the number of bills to give to the customer
printf("Give the customer %d Hundred doller bill(s)!\n", oneHundred);
printf("Give the customer %d Fifty doller bill(s)!\n", fifty);
printf("Give the customer %d Twenty doller bill(s)!\n", twenty);
printf("Give the customer %d Ten doller bill(s)!\n", ten);
printf("Give the customer %d Five doller bill(s)!\n", five);
printf("Give the customer %d One doller bill(s)!\n", one);
// Second send the change variable to the getCoins
// function along with pointers for each type of
// coin. The function will calculate the number of
// coins to give to the customer and return each
getCoins(change, &quarter, &dime, &nickel, &penny);
// Print the number of coins to give to the customer
printf("Give the customer %d Quarter(s)\n", quarter);
printf("Give the customer %d Dime(s)\n", dime);
printf("Give the customer %d Nickel(s)\n", nickel);
printf("Give the customer %d Penny(s)\n", penny);
printf("%d\n", cash);
printf("%.2f\n", change);
printf("$%.2f\n", dif);
return 0;
}
It is working ok, until I print out the number of Nickels, and Pennies to the customer. Instead of giving me a number which would make sense it is giving me a random string of numbers.
For example this is the output for these inputs:
Enter the exact amount of the items (18.37): 123.32
Enter the amount of money given by the customer: 124.00
Wow close to exact change! - No need for cash...
Give the customer 0 Hundred doller bill(s)!
...
Give the customer 0 One doller bill(s)!
After all loops change = 0
Give the customer 2 Quarter(s)
Give the customer 1 Dime(s)
Give the customer 32768 Nickel(s)
Give the customer 1596836443 Penny(s)
0
0.68
$0.68
Now if the program was working correctly, it should say:
2 Quarter(s)
1 Dime(s)
1 Nickel(s)
3 Penny(s)
But I'm getting those random(?) values. Could this be a problem with me not clearing my pointers? I have never worked with a language that uses them, and I have not learned enough to use them properly.
I tried to set all the cash variables (for example oneHundred) to NULL, but it gives me this compiler error:
change.c:204:14: warning: incompatible pointer to integer conversion assigning
to 'int' from 'void *' [-Wint-conversion]
oneHundred = NULL;
^ ~~~~
Any help would be amazing! I am just beginning to learn this language, and I hope this question will give me some insight on how to write better C in the future! Thank you!!
You don't need to set them to NULL be cause they are not pointers, initialized them to 0 like this
cash = oneHundred = fifty = twenty = ten = five = one = quarter = dime = nickel = penny = 0;
NULL is used to initialized pointers to a special value, so you can test against it to check if the pointer is pointing somewhere or if it doesn't.
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.
Question : Program that asks the user to enter an item price value and then show how to pay that amount using the smallest number of $ 50,$20, $10,$5, and $1 bills consist.
Example Output:
Enter Price: 187
Enter Amount to pay: 500
Change is : 313
(6)$50 (1)$10 (3)$1
(0)$20 (0)$5
Here's my code: hope you help me , I am having a hard to in knowing the right formula for it..
#include <stdio.h>
#include <conio.h>
#define p printf
#define s scanf
#define g gotoxy
main()
{
clrscr();
int c1,c2,c3,c4,c5;
int price,amount;
float change;
p("Enter Price: ");s("%d",&price);
p("Enter amount: ");s("%d",&amount);
change=amount-price;
p("Change is : %f ",change);
c1=(change/50);
c2=(0);
c3=(change/change);
c4=(0);
c5=(change/change)+2;
g(5,5);p("(%d) Php 50",c1);
g(5,6);p("(%d) Php 20",c2);
g(18,5);p("(%d)Php 10 \t",c3);p("(%d)Php 1",c5);
g(18,6);p("(%d) Php 5 ",c4);
getch();
return 0;
}
You're on the right track:
change should be a int too (that means you should change %f to %d). You would then correctly determine the number of 50's (note that integer division in C truncates). You should look at % (modulus operator) to get the remaining amount of changes after the 50's are dealt with:
Using your example:
change = 313
fifties = 313/50 (6)
change %= 50 (13)
That means set change to the remainder after dividing itself by 50 (change = change % 50)
twenties = change / 20 (0)
change %= 20 (13)
tens = change / 10 (1)
change %= 10 (3)
This should give you the basic idea of the code you need. You just continue this pattern in order of decreasing denomination.
As noted, use better variable names, don't use those defines, and generally stick to one statement per line (add a newline after semi-colons). This will make your code more readable. You're also using more parentheses than needed, but that's not a big deal.
I would suggest define an array which holds the bill denominations, and an initially empty array of bill counts:
int denoms[5] = {50, 20, 10, 5, 1};
int bills[5] = {0, 0, 0, 0, 0};
for(int i =0; i < 5; ++i)
{
bills[i] = /* do something interesting with denoms[i] here */
change = /* more work for you here */
}
/* output answer */
for(int i =0; i < 5; ++i)
{
if (bills[i] > 0)
p("{%d)$%d", bills[i], denoms[i]);
}
p("\n");
for(int i =0; i < 5; ++i)
{
if (bills[i] == 0)
p("{%d)$%d", bills[i], denoms[i]);
}
p("\n");
void changeloop(int* change, int* counter, int amount) {
while (*change > amount) {
(*counter)++;
(*change) -= amount;
}
}
int main() {
clrscr();
int price; printf("Enter Price: "); scanf("%d", &input);
int amount; printf("Enter Amount: "); scanf("%d", &amount);
int change = amount - price;
int fifties, twenties, tens, fives, ones;
fifties = twenties = tens = fives = ones = 0;
changeloop(&change, &fifties, 50);
changeloop(&change, &twenties, 20);
changeloop(&change, &tens, 10);
changeloop(&change, &fives, 5);
changeloop(&change, &ones, 1);
printf("Fifties: %d\n", fifties);
printf("Twenties: %d\n", twenties);
printf("Tens: %d\n", tens);
printf("Fives: %d\n", fives);
printf("Ones: %d\n", ones);
getch();
return;
}
There's work to do, like input validation and error handling. But the basics are here. The code could be refactored to be much more extensible... but meh.