Answer to Question #296892 in C++ for Program Training

Question #296892

Write a program with total change amount as an integer input, and output the change using the fewest coins, one coin type per line. The coin types are Dollars, Quarters, Dimes, Nickels, and Pennies. Use singular and plural coin names as appropriate, like 1 Penny vs. 2 Pennies. 

Ex: If the input is: 

0 

(or less than 0), the output is: 

No change 

Ex: If the input is: 

45

the output is: 

1 Quarter
2 Dimes 
1
Expert's answer
2022-02-12T04:41:14-0500
# include <iostream>


int main() {
	int change;
	std::cin >> change;
	auto for_one = 
		[&change]
		(const char* single, const char* plural, int coin_val) {
		if (change / coin_val == 1) {
			std::cout << "1 " << single << "\n";
			change -= coin_val;
		}
		else if (change / coin_val) {
			std::cout << change / coin_val << " " << plural << "\n";
			change %= coin_val;
		}
	};


	if (change <= 0) std::cout << "No change";
	else {
		for_one("Dollar", "Dollars", 100);
		for_one("Quarter", "Quarters", 25);
		for_one("Dime", "Dimes", 10);
		for_one("Nickel", "Nickels", 5);
		for_one("Penny", "Pennies", 1);
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog