Skip to content

Instantly share code, notes, and snippets.

@h3llborn
Last active August 29, 2015 14:09
Show Gist options
  • Save h3llborn/7652ff3e077b81b7ad8f to your computer and use it in GitHub Desktop.
Save h3llborn/7652ff3e077b81b7ad8f to your computer and use it in GitHub Desktop.
greedy change algorithm for assignment 4
// Author: Chris Niesel
// Class: 2211A
#include <stdio.h>
/*
Method: pay_amount
input: int dollars, int *twenties, int *tens, int *fives, int *toonies, int *loonie
purpose: determine the best way to change an amount into bills / coins
returns: nothing.
*/
void pay_amount(int dollars, int *twenties, int *tens, int *fives, int *toonies,int *loonie ){
int num; // count of denomination
int denom[] = {20,10,5,2,1}; // currency denominations
int i = 0;// loop 5 times, same as amount of denominations
for(i;i<5;i++){
if(denom[i]<=dollars){ // check if current denom is less than or equal to current dollar amount
num = dollars / denom[i]; // if so then count the amount of times current denom is needed
if(denom[i] == 20) // check what denomination it is
*twenties = num; // store count in pointer value
if(denom[i] == 10)
*tens = num;
if(denom[i] == 5)
*fives = num;
if(denom[i] == 2)
*toonies = num;
if(denom[i] == 1)
*loonie = num;
dollars -= num * denom[i]; // subtract count of denomination from dollar amount
}
}
}
int main(void) {
// initalize counter vars
int dollars, twenties = 0,tens =0,fives =0,toonies = 0,loonie =0;
// ask for input to make change
printf("\nPlease enter a dollar amount: ");
scanf("%d",&dollars);
// generate change
pay_amount(dollars,&twenties,&tens,&fives,&toonies,&loonie);
// print optimum denomination to use
printf("%d x $20\n",twenties);
printf("%d x $10\n", tens);
printf("%d x $5\n",fives);
printf("%d x $2\n",toonies);
printf("%d x $1\n",loonie);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment