breaking cents down into units of currency using C++
Posted by Samath
Last Updated: January 06, 2021

In order to destroy Sauron's ring by throwing it into the volcano Mt. Doom in the heart of Mordor, the hobbits have traveled a long way from their home in the Shire. And they've incurred a lot of expenses along the way. Fifteen dollars for a night at the Prancing Pony Inn, $2.50 for Gandalf's pipe tobacco, $3.85 for foot shampoo, and on and on. It is getting difficult for Frodo to keep track of all their expenses and manage all this loose change. If only they had some sort of magical device that could register their cash, a "cash register" of some sort. Who among you is wise enough to rise the challenge?

Your goal is to make a program that breaks a given number of cents down into units of currency. Your program should first ask the user to enter the total number of cents. It then displays the amount broken down into the individual units of currency (dollars, quarters, nickels, dimes, pennies). An example is shown below, where the user entered 1258 cents. For simplicity, we will use the plural of all currencies, so "1 nickels" is acceptable.


 

#include <iostream>
using namespace std;

int main()
{
int cents;
int dollars, quarters, dimes, nickels, pennies;

cout << "Enter total cents: ";
cin >> cents;

dollars = cents / 100;
cents = cents - dollars*100;
quarters = cents / 25;
cents = cents - quarters*25;
dimes = cents / 10;
cents = cents - dimes*10;
nickels = cents / 5;
cents = cents - nickels*5;
pennies = cents;  

cout << "This corresponds to "
<< dollars << " dollars, "
<< quarters << " quarters, "
<< dimes << " dimes, "
<< nickels << " nickels, and "
<< pennies << " pennies.\n\n";

return 0;
}
Related Content