This example asks the user to type in an amount of money in pounds and pence.
It then determines the optimum way to make this amount using the different kinds of coins available.
The screenshot shows the program running on an Ubuntu laptop, but it can also be compiled and executed on an Apple Mac or Raspberry Pi.
Select and copy the C++ source-code at the bottom of this post.
Paste into a text editor, such as Nano or Geany.
Then save the new file, ending in .cppI used vending.cpp
To compile from the command-line:
g++ -o vending vending.cpp
To run from the command-line:
./vending
Here's the code:
#include <iostream> // Keyboard and screen code
using namespace std; // Names for cout, cin and endl
int main()
{
// Allow user to type in how much money is needed
float moneyValue;
cout << endl << "Enter amount in pounds and pence: ";
cin >> moneyValue;
cout << endl << "- - - - -" << endl << endl;
// If they typed in a sensible value, determine coins needed
if ( cin.good() )
{
// Convert from pounds and pence to whole pennies
int penceValue = moneyValue * 100;
// 8 different kind of coins in UK
float coinValue[] = { 200, 100, 50, 20, 10, 5, 2, 1 };
string coinName[] = { "£2", "£1", "50p", "20p", "10p", "5p", "2p", "1p" };
// Start with first kind of coin
int coinType = 0;
// While there is still money left to process
// determine how many of each type of coin are needed
while ( penceValue > 0 and coinType < 8 )
{
int coinsNeeded = penceValue / coinValue[coinType];
cout << "Need " << coinsNeeded << " " << coinName[coinType] << " coins " << "\t";
penceValue -= ( coinsNeeded * coinValue[coinType] );
cout << penceValue << "p left over" << endl;
coinType += 1;
} // end of while
cout << endl;
return 0; // Error code indicates was successful
}
else
{
cout << "Not valid." << endl;
return 13; // Error code indicates input was not valid
}
}
Find out more - buy the book on Amazon...