Program: Vending machine using while loop and arrays



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 program creates two different arrays: one for the values of the different UK coins and one for the name of each different kind of coin. Starting with the coin that has the largest value, the £2 coin, the program repeatedly determines how many of these coins can be divided into the amount of money remaining, before moving on to the next kind of coin.

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 .cpp
I 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...