136k views
3 votes
3.24 LAB: Exact change

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
how do i code this in c++?

1 Answer

5 votes
Here's an example code in C++ to solve the problem:

#include
using namespace std;

int main() {
int totalChange;

// Get input from user
cout << "Enter total change amount (in cents): ";
cin >> totalChange;

if (totalChange <= 0) {
cout << "No change" << endl;
} else {
int dollars = totalChange / 100;
int quarters = (totalChange % 100) / 25;
int dimes = ((totalChange % 100) % 25) / 10;
int nickels = (((totalChange % 100) % 25) % 10) / 5;
int pennies = (((totalChange % 100) % 25) % 10) % 5;

// Output the result
if (dollars > 0) {
if (dollars == 1) {
cout << dollars << " Dollar" << endl;
} else {
cout << dollars << " Dollars" << endl;
}
}
if (quarters > 0) {
if (quarters == 1) {
cout << quarters << " Quarter" << endl;
} else {
cout << quarters << " Quarters" << endl;
}
}
if (dimes > 0) {
if (dimes == 1) {
cout << dimes << " Dime" << endl;
} else {
cout << dimes << " Dimes" << endl;
}
}
if (nickels > 0) {
if (nickels == 1) {
cout << nickels << " Nickel" << endl;
} else {
cout << nickels << " Nickels" << endl;
}
}
if (pennies > 0) {
if (pennies == 1) {
cout << pennies << " Penny" << endl;
} else {
cout << pennies << " Pennies" << endl;
}
}
}
return 0;
}

The program first asks the user for the total change amount in cents. If the input is less than or equal to 0, the program outputs "No change". Otherwise, it calculates the number of dollars, quarters, dimes, nickels, and pennies needed to represent the total change using integer division and modulo operations. Then, it outputs each coin type with its corresponding amount, taking into account singular and plural coin names.
User Virsir
by
7.8k points