SOURCE FILE: changer0.cpp
#include <iostream>
using namespace std ;
int getAmt() ;
bool amtOK (int amount ) ;
void tellAnswer(int amount) ;
void printErrMsg (int amount) ;
int next (int amountLeft) ;
bool wantsToContinue () ;
int main ()
{
do
{
int amount = getAmt() ;
if ( amtOK( amount ) )
tellAnswer( amount ) ;
else printErrMsg ( amount ) ;
} while ( wantsToContinue() ) ;
cout << endl ;
return 0;
}
/* Prompt for and retun an amount of cents between 1 and 99 */
int getAmt()
{
int amnt ;
cout << "\nPlease input an amount between 1 and 99 cents: " ;
cin >> amnt ;
return amnt ;
}
/* Return true if and only if 1 <= amount <= 99 */
bool amtOK (int amount)
{
return ( (amount > 0) && (amount < 100) ) ;
}
/* Show how to give this amount of money using the fewest coins,
given that 25, 10, 5, and 1 are the coin denominations
available. */
void tellAnswer(int amount)
{
int amtLeft = amount ;
int quarters = 0, dimes = 0, nickels = 0, pennies = 0;
int nextCoin ;
while (amtLeft > 0)
{
nextCoin = next(amtLeft) ;
amtLeft = amtLeft - nextCoin ;
if (nextCoin == 25) quarters++ ;
else if (nextCoin == 10) dimes++ ;
else if (nextCoin == 5) nickels++ ;
else pennies++ ;
}
cout << "quarters: " << quarters << endl ;
cout << "dimes: " << dimes << endl ;
cout << "nickels: " << nickels << endl ;
cout << "pennies: " << pennies << endl << endl ;
}
/* Print the message "Bad Input: Try again." on a line by itself. */
void printErrMsg (int amount)
{
cout << "Bad Input: Try again.\n\n" ;
}
/* figure out which coin to give next if the amount left is
amountLeft. Return the value of the coin */
int next (int amountLeft)
{
int coin ;
if (amountLeft >= 25) coin = 25 ;
else if (amountLeft >= 10) coin = 10 ;
else if (amountLeft >= 5) coin = 5 ;
else coin = 1;
return coin ;
}
/* Return true if the user wants to solve another problem,
else return fals. */
bool wantsToContinue ()
{
char answer ;
cout << "Would you like to make change again? (y/n) " ;
cin >> answer ;
return (answer == 'y') ;
}