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.
Related
I have written a program to calculate compound interest.
Here is the code:
#include <stdio.h>
#include <math.h>
int main(void) {
float value, rate, years,r;
int column = 0, tmp;
printf("Enter money values: ");
scanf("%f",&value);
printf("Enter a interest rate: ");
scanf("%f",&rate);
printf("Enter number of years: ");
scanf("%f",&years);
printf("\nYears ");
tmp = rate + 4;
r = rate;
for (int a = rate; a <= tmp; a++) {
printf(" %d ", a);
column++;
}
for (int b = 1; b <= column; b++) {
printf("\n %d",b);
for (int i = 1; i<= column; i++) {
printf(" %.2f ", (float) pow ( (value)*(1.0+((r/100.0)/(1.0))) , (1.0*b))
r++;
}
r = rate;
printf("\n");
}
// I = P*R*T
// P= AMOUNT (value)
// R=RATE (r)
// T=YEARS (b)
return 0;
}
It asks the user for a value (money), interest rate, number of years and displays the interest rate like so:
Enter money values: 100
Enter a interest rate: 6
Enter number of years: 5
Years 6 7 8 9 10
1 106.00 107.00 108.00 109.00 110.00
2 11236.00 11449.00 11664.00 11881.00 12100.00
3 1191016.00 1225043.00 1259712.00 1295029.00 1331000.00
4 126247696.00 131079600.00 136048896.00 141158160.00 146410000.00
5 13382255616.00 14025517056.00 14693280768.00 15386240000.00 16105100288.00
But my problem is the floating point calculation.
As you may be able to tell the numbers in the output above and very long and have many trailing digits
which i am very confused about.
For example in the 2nd row the first output is 11236.00,
this is wrong since it should be outputting 112.36 but for some reason the decimal has moved
forward two spaces. Why is this? and how could i fix this problem and print the correct solution
with the decimal in the correct place.
You have the value inside the pow. So when you square for two years, you are squaring the amount. Move the (value)* to output the pow call.
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 have asked for the user to enter in several values to calculate an average, however I'd like to also calculate a gradient which uses the inputted values. How do I name these values so I can use them again? Thank you.
Here is what I have thus far:
#include <stdio.h>
int main () {
int n, i;
float num[1000], total=0, mean;
printf("Enter the amount of x-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d", &n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input x-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean=total/n;
printf("The mean of all the x-values entered is %.2f to 2 decimal places", mean);
{
float num[1000], total=0, mean;
printf("Enter the amount of y-values:");
scanf("%d", &n);
while (n <= 0 || n > 1000) {
printf("Print error. The number should in range of 0 to 1000.\n");
printf("Please try to enter the amount again: ");
scanf("%d",&n);
}
for (i = 0; i < n; ++i) {
printf("%d. Input y-value:", i+1);
scanf("%f", &num[i]);
total += num[i];
}
mean = total / n;
printf("The mean of all the y-values entered is %.2f to 2 decimal places", mean);
return 0;
}
}
Naming the variable is really up to you, but `int gradient[NUM_ELEMENTS]; seems appropriate. It is an array, which also seems appropriate if it's purpose is to assist in finding the gradient from a series of numbers.
Steps could be:
1) use printf to ask user for values, specify spaces or commas between values. You can also specify a limit of values. Example printf("enter 5 numbers separated by commas\n:");
2) use scanf or similar to read values from standard input (the terminal) into the array: scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
3) use the array an a function that will compute the gradient.
Simple example:
(where gradient computation, error checking, bounds checking etc. is all left to you)
int get_gradient(int a[5]);
int main(void) {
int gradient[5];
int iGradient=0;
printf("enter 5 numbers separated by commas");
scanf("%d,%d,%d,%d,%d", &gradient[0], &gradient[1], &gradient[2], &gradient[3], &gradient[4]);
iGradient = get_gradient(gradient);
return 0;
}
int get_gradient(int a[5])
{
return [do computation here using array a];
}
Edit:
The above example works only if you know the number of elements at compile time. It uses an int array that has been created on the stack. If you do not know how big of an array you will need until run-time, for example if user input determines the size, then the array size needs to be determined at run-time. One options is to create the variable needed on the heap. (read about stack and heap here) The following uses some techniques different from the simpler version above to get user input, including a function I called get_int(), which uses scanf() in conjunction with strtol(). Here's the example:
int main(void) {
char input[80]={0};
char **dummy={0};
long *gradient = {0};
int iGradient=0;
int arraysize;
int i;
char* fmt = "%[^\n]%*c";
printf("how many numbers will be entered?");
scanf(fmt, input);
arraysize = strtol(input, dummy, 10);
gradient = calloc(arraysize, sizeof(long));
if(gradient)
{
for(i=0;i<arraysize;i++)
{
gradient[i] = get_int();
}
iGradient = get_gradient(gradient, arraysize);
//free gradient when done getting result
free(gradient);
}
return 0;
}
int get_gradient(int *a, int num)
{
int grad = 0, i;
//do something here to compute gradient
return grad;
}
long get_int(void)
{
char input[80]={0};
char **dummy={0};
char* fmt = "%[^\n]%*c";
printf("Enter integer number and hit return:\n");
scanf(fmt, input);
return strtol(input, dummy, 10);
}
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)
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.