In: Computer Science
C++
19.32 LAB: Exact change - functions
Write a program with total change amount as an integer input that outputs 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, the output is:
no change
Ex: If the input is:
45
the output is:
1 quarter 2 dimes
Your program must define and call the following function.
Positions 0-4 of coinVals should contain the number of dollars,
quarters, dimes, nickels, and pennies, respectively.
void ExactChange(int userTotal, vector<int>&
coinVals)
Note: This is a lab from a previous chapter that now requires the use of a function.
#include <iostream> #include <vector> using namespace std; void ExactChange(int userTotal, vector<int>& coinVals) { coinVals.clear(); coinVals.push_back(userTotal / 100); userTotal %= 100; coinVals.push_back(userTotal / 25); userTotal %= 25; coinVals.push_back(userTotal / 10); userTotal %= 10; coinVals.push_back(userTotal / 5); userTotal %= 5; coinVals.push_back(userTotal); } int main() { vector<int> coins; int value; cin >> value; if (value <= 0) { cout << "no change" << endl; } else { ExactChange(value, coins); if (coins[0] != 0) cout << coins[0] << " " << (coins[0] == 1 ? "dollar" : "dollars") << endl; if (coins[1] != 0) cout << coins[1] << " " << (coins[1] == 1 ? "quarter" : "quarters") << endl; if (coins[2] != 0) cout << coins[2] << " " << (coins[2] == 1 ? "dime" : "dimes") << endl; if (coins[3] != 0) cout << coins[3] << " " << (coins[3] == 1 ? "nickel" : "nickels") << endl; if (coins[4] != 0) cout << coins[4] << " " << (coins[4] == 1 ? "penny" : "pennies") << endl; } return 0; }