Result of previous line (C programming) - c

I'm taking a C programming class and I'm doing practice questions in the book. One of the questions is:
Write a program that asks the user to enter a U.S. dollar amount and then shows how to pay that amount using the smallest number of $20, $10, $5, %1 bills:
The sample is as follows:something right away that I may have overlooked when trying my code.
Enter a dollar amount: 93 (user inputted)
$20 bills: 4
$10 bills: 1
$5 bills: 0
$1 bills: 3
What I have so far is:
#include <stdio.h>
int main (void)
{
int cash;
printf("Enter a dollar amount: ");
scanf("%d", &cash);
printf("$20 bills = %d\n", cash / 20);
printf("$10 bills = %d\n", cash / 10);
printf("$5 bills = %d\n", cash / 5);
printf("$1 bills = %d\n", cash / 1);
return 0;
}
The problem is, the book suggests dividing the input number (93) by 20, and since I'm using int instead of float, that leaves 4 instead of 4.65. Then it suggests subtracting the result of that times 20, from 93, leaving 13, and repeating that for each one. So it would be:
93/20=4
13/10=1
3/1=3
How can I get the printf("$10 bills = %d\n", cash / 10); line to recognize the value left by the previous line, printf("$20 bills = %d\n", cash / 20);? I had originally tried to put most of it on the 20 bill line, like cash / 20 * 20, but it just displayed 80 on that line instead of the next line.

I think you are mistaken a bit here. As you said, values are not left by the previous printf. You need to update the value of the variable cash. Here is what could help:
#include <stdio.h>
int main (void)
{
int cash;
printf("Enter a dollar amount: ");
scanf("%d", &cash);
printf("$20 bills = %d\n", cash / 20);
cash = cash % 20;
printf("$10 bills = %d\n", cash / 10);
cash = cash % 10;
printf("$5 bills = %d\n", cash / 5);
cash = cash % 5;
printf("$1 bills = %d\n", cash);
return 0;
}
The modulo (%) operator gives you back the remainder after performing the division. Hence:
93 % 20 = 13
13 % 10 = 3
and so on.

cash is a variable meaning that it can vary in value. In other words, you can change the value of cash.
The % operator returns the remainder from a division. So if you do cash = 93 % 20; then cash should contain 13.
Remember that you can also set cash in relation to itself. So cash = cash % 20; would set cash to the value of the remainder of cash / 20.

Also, for the record,
you may want to put the bill values in a table
and iterate on this to avoid copy-pasted code:
int main()
{
int billval[] = { 20, 10, 5, 1, 0 };
int cash, i;
printf("Enter a dollar amount: ");
scanf("%d", &cash);
for(i = 0; billval[i]; i++) {
printf("$%d bills = %d\n", billval[i], cash / billval[i]);
cash = cash % billval[i];
}
return 0;
}
Here, the billval table is zero-terminated so we know when to stop
iterating<

You may have to use the modulo operator (%) which returns the remainder of the division of two numbers (for example, 93 % 20 equals 13).
For example :
int cash = 93;
int twenty, ten, five, one;
twenty = cash / 20;
cash = cash % 20;
ten = cash / 10;
cash = cash % 10;
/* etc. */

int main(){
int cash, bills_20, bills_10, bills_5, bills_1;
printf("Enter dollars amount: ");
scanf("%d",&cash);
bills_20=cash/20;
printf("$ 20 bills: %d\n",bills_20);
bills_10=(cash-bills_20*20)/10;
printf("$ 10 bills: %d\n",bills_10);
bills_5=(cash-bills_20*20-bills_10*10)/5;
printf("$ 5 bills: %d\n",bills_5);
bills_1=(cash-bills_20*20-bills_10*10-bills_5*5);
printf("$ 1 bills: %d\n",bills_1);
return 0;}

Thanks for all the help. Delroth & Imagist (well FooBar too, I dont know how I missed his comment while I was testing the theory since its exactly what I did) reminded me by simply adding another value for cash after each line would produce the result I was looking for.
#include <stdio.h>
int main (void)
{
int cash;
printf("Enter a dollar amount: ");
scanf("%d", &cash);
printf("$20 bills = %d\n", cash / 20);
cash = cash % 20;
printf("$10 bills = %d\n", cash / 10);
cash = cash % 10;
printf("$5 bills = %d\n", cash / 5);
cash = cash % 5;
printf("$1 bills = %d\n", cash / 1);
cash = cash % 1;
return 0;
}
thats using the modulo % which hasnt been covered in the book yet, I'm going to try it again the way Pax suggested. Thanks again for the help

I would put another integer at the top to represent the number of bills for the current denomination:
int billCount;
then replace each section (except the $1 section) with:
billCount = cash / 20; // billCount <- 93/20 = 4.
printf("$20 bills = %d\n", billCount);
cash -= (billCount * 20); // cash <- cash - (4*20) = 13.
You can do it with modulo operators with less lines of code but the above code is what the suggestion from the book is pointing you toward.
Try to work it out using just the information above, if possible (it'll make you a better programmer). If you still can't do it, here's my full solution.
#include <stdio.h>
int main (void) {
int cash, count;
printf("Enter a dollar amount: ");
scanf("%d", &cash);
count = cash / 20;
printf("$20 bills = %d\n", count);
cash -= (count * 20);
count = cash / 10;
printf("$10 bills = %d\n", count);
cash -= (count * 10);
count = cash / 5;
printf(" $5 bills = %d\n", count);
cash -= (count * 5);
printf(" $1 bills = %d\n", cash);
return 0;
}

Related

Change calculator not returning correct answer

I'm having some trouble with a program I have to write for an exercise in my uni course. I have to create a change calculator that asks the user for the price of an item and how much they've put into the machine but my program returns the wrong answer in the amount of change given back to the user. What have I done wrong?
#include <stdio.h>
int main()
{
int cost;
int money;
int change;
int remainder;
int fiftyP;
int twentyP;
int tenP;
int fiveP;
int twoP;
int oneP;
printf("What is the price of the item: ");
scanf_s("%d", &cost);
printf("How much have you put into the machine: ");
scanf_s("%d", &money);
while (cost > 99 || money > 100)
{
printf("Please enter no larger than 99p for cost and 100p for money inserted\n");
printf("What is the price of the item: ");
scanf_s("%d", &cost);
printf("How much have you put into the machine: ");
scanf_s("%d", &money);
}
change = money - cost;
fiftyP = change / 50;
remainder = change % 50;
twentyP = remainder / 20;
remainder = change % 20;
tenP = remainder / 10;
remainder= change % 10;
fiveP = remainder / 5;
remainder = change % 5;
twoP = remainder / 2;
remainder = change % 2;
oneP = remainder / 1;
printf("Number of 50p coins is %d\nNumber of 20p coins is %d\nNumber of 10p coins is %d\nNumber of 5p coins is %d\nNumber of 2p coins is %d\nNumber of 1p coins is %d ", fiftyP, twentyP, tenP, fiveP, twoP, oneP);
}
After calculating the value of fiftyP, you're using change to calculate each successive remainder while using remainder to calculate each coin count. You should instead be using change in all places:
change = money - cost;
fiftyP = change / 50;
change= change % 50;
twentyP = change/ 20;
change= change% 20;
tenP = change/ 10;
change= change% 10;
fiveP = change/ 5;
change= change% 5;
twoP = change/ 2;
change= change% 2;
oneP = change/ 1;

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]);

C pointer giving random value

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.

change counter c program not displaying correct output

I am working on a change counter program and I am stuck, I have searched here and 2 other coding forums, google and youtube, but haven't found an answer yet...my program sucks and i am brand new to c/c++...my txt book is not here yet so I am trying to read every every thing i can get my hands on till it gets here
This is what the output should be in the console window:
Welcome to Change Counter by Jo Mama!!
Please enter the total amount of purchase: $52.173
$52.173
Please enter amount of money tendered: $60
$60.00
Your change is: $7.83
-------------------------------------------
Twenties : 0
Tens : 0
Fives : 1
Ones : 2
Quarters : 3
Dimes : 0
Nickels : 1
Pennies : 3
-------------------------------------------
Thank you for using Change Counter!
here is what i have so far...
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
// define variables here
long double numberOfTwenties = 0;
long double numberOfTens = 0;
long double numberOfFives = 0;
long double numberOfOnes = 0;
long double numberOfQuarters = 0;
long double numberOfDimes = 0;
long double numberOfNickels = 0;
long double numberOfPennies = 0;
double purchasePrice = 0;
double amountTendered = 0;
double amountOfChange = 0;
double amountOfChangeCents = 0;
// start program here
printf("Welcome to the change counter by Josh Manion!!\n\n");
printf("Please enter the total amount of purchase: $");
scanf("%d", &purchasePrice);
printf("%d\n", purchasePrice);
printf("Please enter amount of money tendered: $");
scanf("%d", &amountTendered);
printf("%d\n", amountTendered);
//do change calculations here
amountOfChange = (amountTendered - purchasePrice);
printf("Your change is: $%d\n", amountOfChange);
numberOfTwenties = amountOfChange / 20;
//amountOfChange = numberOfTwenties %= amountOfChange;
numberOfTens = (amountOfChange / 10);
numberOfFives = (amountOfChange / 5);
numberOfOnes = (amountOfChange / 1);
numberOfQuarters = (amountOfChange * 0.25);
// print change calculations here
printf("---------------------------------------------\n");
//display denominations of change here
printf("Twenties: %d\n", numberOfTwenties);
printf("Tens: %d\n", numberOfTens);
printf("Fives: %d\n", numberOfFives);
printf("Ones: %d\n", numberOfOnes);
printf("Quarters: %d\n", numberOfQuarters);
printf("Dimes: %d\n", numberOfDimes);
printf("Nickels: %d\n", numberOfNickels);
printf("Pennies: %d\n", numberOfPennies);
printf("---------------------------------------------\n");
printf("Thank you for using the Change Counter!");
getchar();
return EXIT_SUCCESS;
}
The problem is that my program doesn't work, it shows the change after the prompt but not the breakdown of denominations, I am sposed to use the "%" to bring down the change amount, but i havent found any examples. I don't know what else to say... besides I'm new and this post will help a lot of people...
Your program has undefined behaviour : you must use %Lf as the printf modifier to print a long double (same issue with your usage of scanf)

C Program Exercise. Simple transaction report

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.

Resources