user3353201
user3353201

Reputation:

Dollar change program in c

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!

Upvotes: 0

Views: 1839

Answers (3)

Robᵩ
Robᵩ

Reputation: 168836

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;
}

Upvotes: 2

Kissiel
Kissiel

Reputation: 1955

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...

Upvotes: 2

abligh
abligh

Reputation: 25179

Not as you have written it. But as you've written it it only finds the number of 20s.

Upvotes: 0

Related Questions