Author Topic: Change calculator  (Read 3670 times)

louiecerv

  • Moderator
  • User
  • *****
  • Posts: 85
Change calculator
« on: November 27, 2005, 11:07:08 AM »
PROBLEM

Write an application that reads a purchase price and amount tendered then displays the change in dollars, quarters, dimes, nickels and pennies.  

SOLUTION

Code: [Select]

#include <iostream>
using namespace std;

int main()
{
    float price, tendered, change;
    int cents, dollars, quarters, dimes, nickels, pennies;
    int remainder;
    cout << "-- CHANGE CALCULATOR --" << endl;
    cout << "This program reads a purchase price and an amount " << endl;
    cout << "tendered and then displays the change in dollars, " << endl;
    cout << "quarters, dimes, nickels and pennies." << endl << endl;
    cout << "Purchase Price :  $ ";
    cin >> price;
    do {
        cout << "Amount Tendered:  $ ";
        cin >> tendered;
        if (tendered < price)
        {
            cout << "Amount tendered is not enough.  Enter correct amount." << endl;
        }
    } while (tendered < price);
   
    change = tendered - price;
    cents =  static_cast<int>(change * 100.0);    
    cout << "\nYour change is :  $ " << change << endl;
   
    dollars = cents/100;
    remainder = cents%100;

    cout << "                  "
         << dollars << " one-dollar bill(s)" << endl;
    if (remainder > 0)
    {
        quarters = remainder/25;
        remainder = remainder%25;
        cout << "                  "
             << quarters << " quarter(s)" << endl;
        if (remainder > 0)
        {
        dimes = remainder/10;
        remainder = remainder%10;
        cout << "                  "
             << dimes << " dime(s)" << endl;
            if (remainder > 0)
            {
                nickels = remainder/5;
                remainder = remainder%5;
                cout << "                  "
                     << nickels << " nickel(s)" << endl;
                if (remainder > 0)
                {
                    pennies = remainder;
                    cout << "                  "
                         << pennies << " pennies(s)" << endl;
                }                
            }
        }
    }
   
    system("PAUSE");
    return 0;
}


Highlights:
use of error handling using do-while (avoids error when tendered amount is less than price)
use of nested If statements
use of modulus division
Analyze. Design. Develop. Debug. Deploy. Maintain.