I'm attempting to write a program in which:
The purpose is to use an array to hold the values of the coins, so I "can write a general purpose change calculator that can be used for any coinage by changing the contents of the array".
Here is my code:
void vendingMachine()
{
// Declarations
#define ARRAY_LENGTH 6
int itemCost;
int amountEntered;
int fifty, twenty, ten, five, two, one;
int remainder;
// User input
printf("Please enter the cost of the item in pence: ");
scanf_s("%d", &itemCost);
while (itemCost <= 0 || itemCost > 99)
{
printf("You've entered an invalid amount. Please enter an amount between 1p and 99p: ");
scanf_s("%d", &itemCost);
}
printf("Please enter the amount entered into the machine in pence: ");
scanf_s("%d", &amountEntered);
while (amountEntered <= 0 || amountEntered > 100)
{
printf("You've entered an invalid amount. Please enter an amount between 1p and 100p: ");
scanf_s("%d", &amountEntered);
}
while (amountEntered < itemCost)
{
printf("You've entered an invalid amount. Please enter an amount equal to or higher than the cost of the item: ");
scanf_s("%d", &amountEntered);
}
// Program to determine if the customer is owed any change and, if so, how much is owed
if (amountEntered == itemCost)
{
printf("No change is owed to the customer");
}
else if (amountEntered > itemCost)
{
int change = amountEntered - itemCost;
printf("The amount of change owed to the customer is: %d pence, broken down as follows: \n", change);
fifty = change / 50;
remainder = change % 50;
twenty = remainder / 20;
remainder = remainder % 20;
ten = remainder / 10;
remainder = remainder % 10;
five = remainder / 5;
remainder = remainder % 5;
two = remainder / 2;
remainder = remainder % 2;
one = remainder;
// Program to store the change in an array
int count[ARRAY_LENGTH];
count[0] = fifty;
count[1] = twenty;
count[2] = ten;
count[3] = five;
count[4] = two;
count[5] = one;
for (int i = 0; i < ARRAY_LENGTH; i++)
{
count[i] = 0;
}
for (int i = 0; i < ARRAY_LENGTH; i++)
{
printf("The number of %d coins is: %d\n", //I don't know what to do here);
}
}
}
Store the type of coins in an array as well, e.g.
const int coins[ARRAY_LENGTH] = { 50, 20, 10, 5, 2, 1 };
Then you can easily refer to them in your loop:
printf("The number of %d coins is: %d\n", coins[i], count[i]);
This also allows you to perform your modulo calculations in a loop.