Write a C program to read a rupee amount (integer value) and break it
up into the smallest possible number of bank notes.
Assume bank notes are in the denominations 2000, 500, 200, 100, 50, 20
and 10.
I am trying to pass amount into the denCAL() function and want to update it everytime the function is called but the value of amount remains same.
Please provide the solution for my problem and a better approach for the solution and also do le me know some good programming practises which are missing here.
#include <stdio.h>
int amount, note, den;
int denCAL(amount, den){
note = amount/den;
amount -= note*den;
printf("Number of %d notes are:%d\n", den, note);
}
int notes(){
printf("Enter the amount in rupees: ");
scanf("%d", &amount);
if(amount >= 2000){
denCAL(amount, 2000);
}
if(amount >= 500){
denCAL(amount, 1000);
}
if(amount >= 200){
denCAL(amount, 500);
}
if(amount >= 100){
denCAL(amount, 100);
}
if(amount >= 50){
denCAL(amount, 50);
}
if(amount >= 20){
denCAL(amount, 20);
}
if(amount >= 10){
denCAL(amount, 10);
}
}
int main(){
notes();
}
OUTPUT
Enter the amount in rupees: 30020
Number of 2000 notes are: 15
Number of 1000 notes are: 30
Number of 500 notes are: 60
Number of 100 notes are: 300
Number of 50 notes are: 600
Number of 20 notes are: 1501
Number of 10 notes are: 3002
int nominals[] = {2000, 500, 200, 100, 50, 20, 10, 0};
void getNominals(unsigned money, int *result)
{
int *nm = nominals;
while(*nm && money)
{
*result++ = money / *nm;
money %= *nm++;
}
}
int main(void)
{
int result[sizeof(nominals) / sizeof(nominals[0])] = {0};
getNominals(30020, result);
for(size_t index = 0; nominals[index]; index++)
{
printf("%d = %d\n", nominals[index], result[index]);
}
}
But in your code you need:
add the return statement:
int denCAL(amount, den)
{
int note = amount/den;
amount -= note*den;
printf("Number of %d notes are:%d\n", den, note);
return amount;
}
and then in every if change denCAL(amount, ...); to
amount = denCAL(amount, ...);
The reason why you're not updating your amount variable, even considering it's a global, it's because in your function denCAL(), by passing amount as a parameter, you're accessing a copy of it. Also you need to specify the type of the input parameters in your function prototype. You should change the code like this:
void denCAL(int den){ // amount is global, no need to pass it
note = amount/den;
amount -= note*den;
printf("Number of %d notes are:%d\n", den, note);
}
void notes(){
printf("Enter the amount in rupees: ");
scanf("%d", &amount);
if(amount >= 2000){
denCAL(2000);
}
/* rest of code */
}
Another approach you could use, instead of using a global variable, is to use pointers for example. You could define amount inside notes(), and remove the global you've already declared.
void denCAL(int* amount, int den){ // passing amount by ADDRESS (so it gets modified)
note = (*amount)/den;
(*amount) -= note*den;
printf("Number of %d notes are:%d\n", den, note);
}
void notes(){
int amount;
printf("Enter the amount in rupees: ");
scanf("%d", &amount);
if(amount >= 2000){
denCAL(&amount, 2000);
}
/* rest of code */
}
Related
I need some advice or hints about how to calculate the average of insurance, tax, gross and net salary. Just need some enlightment.
Tried to add average function before but it seems that its hard to get the value from other function.
Any ideas? This code is used to find the salary of employee and its average.
char EmpName[50];
int EmpID, EmpAge, EmpNum, i;
float gross_salary, net_salary;
float insurance, tax, total, total_insurance, total_tax;
int main()
{
int i;
FILE *file;
file = fopen("UserDetails.txt", "wt");
printf("Number of Employee to process: ");
scanf("%d", &EmpNum);
i = 1;
EmployeeName: while( i <= EmpNum)
{
printf("\nEmployee name: "); scanf("%s", &EmpName);
if (strlen(EmpName) <= 50){
EmployeeID: printf("Employee ID: "); scanf("%d", &EmpID);
if (EmpID >= 1000 && EmpID <= 9999){
EmployeeAge: printf("Employee Age: "); scanf("%d", &EmpAge);
if (EmpAge >= 18 && EmpAge <= 99){
printf("Employee Salary: "); scanf("%g", &gross_salary);
if (gross_salary >= 0.0 && gross_salary <= 9999.99){
goto Total;
}
}
else{
printf("\nInvalid Input!\nEmployee Age Is Between 18 To 99\n");
goto EmployeeAge;
}
}
else{
printf("\nInvalid Input!\nEmployee ID Number is Between 1000 To 9999\n");
goto EmployeeID;
}
}
else{
printf("\nInvalid Input!\nMax Character is 50\n");
goto EmployeeName;
}
Total: printf("\n");
SetInsurance(EmpAge);
IncomeTax(gross_salary);
TaxDeduction(tax);
InsuranceDeduction(insurance);
NetSalary();
Average(insurance,gross_salary,net_salary);
i++;
fprintf(file, "Employee name: %s\n", EmpName); //print data inside file
fprintf(file, "Employee ID: %d\n", EmpID);
fprintf(file, "Employee Age: %d\n", EmpAge);
fprintf(file, "Employee Salary: %g\n\n", gross_salary);
}
fclose(file);
}
float SetInsurance(int x){
while (i <= EmpNum){
if (x <= 35)
insurance = 110;
else if (x >=36 && x <= 65)
insurance = 160;
else if (x > 65)
insurance = 250;
else
printf("Under Age!");
total = insurance;
printf("\nInsurance: %.2f\n", total);
return total;i++;
};
}
float IncomeTax(float salary) {
int i = 0;
while(i < EmpNum){
if (salary <= 999.99)
tax = 0;
else if (salary >= 1000 && salary <= 2999.99)
tax = 2.5;
else if (salary >= 3000)
tax = 5;
else
printf("Invalid Input!\n");
printf("Income Tax Rate: %.2f%\n", tax);
return tax;
i++;
}
}
float InsuranceDeduction(float insurance){
if (insurance == 110){
total_insurance =+ 110;
}else if (insurance == 160){
total_insurance =+ 160;
}else if (insurance == 250){
total_insurance =+ 250;
}
return total_insurance;
}
float TaxDeduction(float tax){
if(tax == 2.5){
total_tax = gross_salary * 0.025;
}else if(tax == 5){
total_tax = gross_salary * 0.05;
}
return total_tax;
}
void NetSalary(){
total = TaxDeduction(tax) + InsuranceDeduction(insurance);
net_salary = gross_salary - total;
printf("Net Salary: RM%.2f\n", net_salary);
}
I order to solve the problem you face, I'd follow the recomendations you have received from other responses, and in addition:
If you fopen() a file, just check that the returned pointer is valid, as you can have several errors derived of:
Not having permissions to read the file.
file doesn't exist.
and these should be handled before you start processing the file.
Second, You don't need to store the data from the file, except for error purposes (it's preferable if you say that Martina Navratilova cannot be paying such ridiculous amount of taxes than saying that record 6437 in the file has a ridiculous amount of taxes to be payd -- you should search for it by counting, while your program has already done it)
If I would to decide how the input file is formatted, I should make a two line record, one line to specify the user name (which so, can have spaces embedded, as the new line marks the end of the name) so it can be read with fgets(), and a second line with all the numeric data you are going to fscanf(), after the sequence is done, you have all the data for a single user. Another possibility (to allow the name with spaces) is to put the name as the last field of the data file, so you can read all the last field characters upto the \n as the user name. This would allow to put each user in one single line
"I need some advice or hints., ...,any idea?"
First: Read and act on each of suggestions in first 3 comments under your post from #Chux.
Other suggestions:
Avoid using goto tag ... :tag statements to traverse code.
Create functions that can be called to do a simple task, then return.
Use a struct to contain related data when there can be more that one related data set.
Change
char EmpName[50];
int EmpID, EmpAge, EmpNum, i;
float gross_salary, net_salary;
float insurance, tax, total, total_insurance, total_tax;
To for example: (Note, not all these members may be necessary, depending on how you finally implement the records needed for each employee.)
typedef struct {
char EmpName[50];
int EmpID;
int EmpAge;
double gross_salary;
double net_salary;
double insurance;
double total_insurance; //may not be necessary in struct
double tax;
double total_tax; //may not be necessary in struct
}account_s;
Note, if "total" members are to be used as totals for all employees, then they should probably not be a members in the struct.
Create instance(s) of this struct in local space, Eg.
int main(void)
{
int EmpNum = 0;
...
printf("Enter number of Employees to process: ");
scanf("%d", &EmpNum);
account_s account[EmpNum];//creates an array of instances of account_s
memset(account, 0, sizeof account);//initializes array
Incorporate account_s into functions as return type, and/or function parameters. Eg.
The following is a very brief, but compilable and runable example to illustrate several things including how to pass a single function argument containing all the information needed to update and contain employee information (via struct).
//prototypes
void populateAccounts(int count, account_s record[count]);
void SetInsurance(account_s *record);
double Get_ave_salery(int c, account_s *account);
int main(void)
{
int EmpNum = 0;
printf("Number of Employee to process: ");
scanf("%d", &EmpNum);
account_s account[EmpNum];//creates an array of instances of account_s
memset(account, 0, sizeof account);//initializes array
populateAccounts(EmpNum, account);
double ave_salary = Get_ave_salery(EmpNum, account);
printf("Average Gross Salary: %lf\n", ave_salary);
return 0;
}
void populateAccounts(int count, account_s record[count])
{
//Read in information for each account
for(int i=0; i<count; i++)
{
printf("\nEnter employee name: ");
scanf("%s", record[i].EmpName);
printf("\nEnter employee ID: ");
scanf("%d", &record[i].EmpID);
printf("\nEnter employee Age: ");
scanf("%d", &record[i].EmpAge);
printf("\nEnter employee Salary: ");
scanf("%lf", &record[i].gross_salary);
SetInsurance(&record[i]);//function to set insurance via function argument
// etc.
}
}
void SetInsurance(account_s * record){
if (record->EmpAge <= 35)
record->insurance = 110;
else if (record->EmpAge >=36 && record->EmpAge <= 65)
record->insurance = 160;
else if (record->EmpAge > 65)
record->insurance = 250;
else
printf("Under Age!");
// total = record->insurance;
printf("\nInsurance: %.2f\n", record->insurance);
}
double Get_ave_salery(int c, account_s *account)
{
double ave = 0.0;
double sum = 0.0;
for(int i=0; i<c; i++)
{
sum += account[i].gross_salary;
}
return sum/c;
}
There is more for you to do here, but this should help you to get started.
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.
I'm trying to get my calcCost function to work now. It doesn't carry over the area variable. Any ideas why it doesn't work? I got the calcArea function working,but can I use the area values for the calcCost area values? I started trying to put a pointer in there, but I'm not familiar with them a whole lot yet.
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
// Define Constants
#define SALESTAX .07
#define TILEONE 0.78
#define TILETWO 1.59
#define TILETHREE 0.89
#define TILEONECASE 17.44
#define TILETWOCASE 10.89
#define TILETHREECASE 15.50
#define TILESIZE1 2.25
#define TILESIZE2 0.97222
#define TILESIZE3 1.77777
// Prototypes
void welcomeMessage(void);
char SelectChoice();
double getLength();
double getWidth();
double calcArea(double len, double wid);
double calcCost(double area);
void endMessage(void);
//integar return type, parameters are void,Richard's Flooring main function allows users to calculate room area and buy flooring.
int main (void)
{
//declare variables
double len, wid, area, tileNeeded,subTotal, taxTotal, total,cost;
double *dp;
char answer, myChoice;
dp = &area;
// Greets users and identifities program.
welcomeMessage ();
//Loop continues until user is done calculating area and buying flooring.
printf("Choice | Dimesions | Price | Sq.FT.per case|\n 1 | 18 x 18 | $%.2lf | 17.44 |\n 2 | 7 x 20 | $%.2lf | 10.89 |\n 3 | 16 x 16 | $%.2lf | 15.50 |\n",TILEONE, TILETWO, TILETHREE);
myChoice = SelectChoice();
len = getLength();
wid = getWidth();
// calcArea function is a double return type, it calculates the Area entered in by the user, its parameters are double len and double wid
area = calcArea(len,wid);
printf("The area of your room is: %g square feet.\n",area);
calcCost(area);
//Provides users with publisher's name.
endMessage ();
return 0;
}
// no return type, tells users what kind of program they are using, and voids any parameters.
void welcomeMessage (void)
{
printf("Welcome to Richard's Flooring\n");
system ("pause");
return ;
}
// no return type, allows user to select choice
char SelectChoice()
{
char myChoice;
do
{
printf("\nWhich tile choice would you like: ");
scanf(" %c", &myChoice);
switch(myChoice)
{
case '1':
printf("You chose choice: 1");
break;
case '2':
printf("You chose choice: 2");
break;
case '3':
printf("You chose choice: 3");
break;
default:
printf("\nINVALID CHOICE 1 - 3 only!");
}
}
while (myChoice > '3'|| myChoice < '1');
return myChoice;
}
double getLength()
{
double len;
// loop continues until positive numbers are entered.
do
{
printf("\nEnter length of room in feet: ");
scanf(" %lf", &len);
if (len <= 0)
printf("\nLength must be positive number.");
}
while (len <=0);
return len;
}
double getWidth()
{
double wid;
// loop continues until positive numbers are entered.
do
{
printf("\nEnter width of room in feet: ");
scanf(" %lf", &wid);
if (wid <= 0)
printf("\nWidth must be positive number.");
}
while (wid <=0);
return wid;
}
// Double return type, which is returning Area. Calculates the Area in a square or rectangle with the formula length * width. Accepts parameters from double len and double wid.
double calcArea(double len, double wid)
{
double area;
area = (len * wid);
return area;
}
double calcCost(double area)
{
SALESTAX ;
double len, wid, tileNeeded,subTotal, taxTotal, total,cost;
char answer, myChoice;
area = calcArea(len,wid);
do
{
char myChoice;
if (myChoice == '1')
{
tileNeeded = area/TILESIZE1;
}
else if (myChoice == '2')
{
tileNeeded = area/TILESIZE2;
}
else if (myChoice == '3')
{
tileNeeded = area/TILESIZE3;
}
printf("You will need %.2lf pieces of tile\n", tileNeeded);
subTotal = tileNeeded * TILETHREE;
printf("Your subtotal is: $%.2lf \n", subTotal);
taxTotal = subTotal * SALESTAX;
printf("Your sales tax comes out to be: $%.2lf \n", taxTotal);
total = taxTotal + subTotal;
printf("Your grand total is: $%.2lf \n",total);
printf("Would you like to measure another room?\n y or n:");
scanf(" %c", &answer);
}
while (answer == 'y'|| answer == 'Y');
}
// no return type, tells users Richard made the program, voids any parameters
void endMessage (void)
{
printf("\nThese results were provided by Richard Triplett\n");
system ("pause");
return ;
}
In main you have these lines which calculate the area and pass it to calcCost:
area = calcArea(len,wid);
printf("The area of your room is: %g square feet.\n",area);
calcCost(area);
This should work correctly but in calcCost you have:
double len, wid, tileNeeded,subTotal, taxTotal, total,cost;
char answer, myChoice;
area = calcArea(len,wid);
This recalculates the area on the basis of the len and wid variables defined in calcCost. Both of these are never set to a specific value and thus their values are indeterminate which leads to the overall area being indeterminate.
If you remove the area = calcArea(len,wid); line from calcCost then you will at least be using the correct value of area.
You will also have issues with myChoice as again this is redefined within calcCost and will have an indeterminate value. The simplest solution is probably to make myChoice an additional parameter to calcCost and pass it in from main.
The do loop in calcCost also doesn't work as required. It would return exactly the same answer every time 'y' or 'Y' was pressed. The do loop should probably be migrated into main but I have just removed it entirely for now.
Changes needed:
in main
calcCost(area,myChoice);
in calcCost
double calcCost(double area, char myChoice)
{
double tileNeeded,subTotal, taxTotal, total,cost;
if (myChoice == '1')
{
tileNeeded = area/TILESIZE1;
}
else if (myChoice == '2')
{
tileNeeded = area/TILESIZE2;
}
else if (myChoice == '3')
{
tileNeeded = area/TILESIZE3;
}
printf("You will need %.2lf pieces of tile\n", tileNeeded);
subTotal = tileNeeded * TILETHREE;
printf("Your subtotal is: $%.2lf \n", subTotal);
taxTotal = subTotal * SALESTAX;
printf("Your sales tax comes out to be: $%.2lf \n", taxTotal);
total = taxTotal + subTotal;
printf("Your grand total is: $%.2lf \n",total);
}
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.
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.