I have got an assignment in which I should program a simple teller machine which takes an amount of 10 dollar bills and exchanges these to 100, 50, 20 and 10 dollar bills. The least amount of bills should be returned.
The assignment focuses a lot on pointers and I am starting to doubt if what I do is good programming style because I believe I take the pointer to a pointer (e.g. &*balance)
Is this a good way to do it or should I rewrite it?
This is my my main:
int main(void) {
int amount = 0; // Amount of 10 dollar bills
int balance = 0; // Total balance (in dollars)
int hundred = 0, fifty = 0, twenty = 0, ten = 0; // Amount of bills calculated
// Set number of 10 dollar bills
printf("Enter amount of 10 dollar bills: ");
scanf("%d", &amount);
// Set balance to user's 10 dollar bills
valueOfBills(&balance, &amount, BILL_VALUE_TEN);
// Calculate amount of bills for the different types
amountOfBills(&balance, &hundred, &fifty, &twenty, &ten);
}
In my main I call amountOfBills() which is a procedure which counts how many of each bill to return:
void amountOfBills(int *balance, int *hundred, int *fifty, int *twenty, int *ten) {
/* To end up with the least amount of bills, we will start with bills with the largest value */
// Calculate amount of 100 dollar bills
amountOfBillsForBillValue(&*hundred, &*balance, BILL_VALUE_HUNDRED);
// Calculate amount of 50 dollar bills
amountOfBillsForBillValue(&*fifty, &*balance, BILL_VALUE_FIFTY);
// Calculate amount of 20 dollar bills
amountOfBillsForBillValue(&*twenty, &*balance, BILL_VALUE_TWENTY);
// Calculate amount of 10 dollar bills
amountOfBillsForBillValue(&*ten, &*balance, BILL_VALUE_TEN);
}
In amountOfBills() I call amountOfBillsForBillValue() which counts how many of a specific bill (e.g. 100 dollar bills) to return:
void amountOfBillsForBillValue(int *storeAmount, int *balance, int billValue) {
/* We don't want to do anything if the balance is 0
therefore we will just return to avoid any calculations */
if (balance == 0) return;
// Calculate amount
*storeAmount = *balance / billValue;
// Set balance
*balance %= billValue;
}
In amountOfBills() I use &*balance. Should I do this another way or is it fine to do so?
&*cancels each other. Justbalancewill do you the same service as&*balanceand with two fewer characters. On the other hand if you just want to remember that it’s poiner, using the&*does not do any harm and the compiler will know well enough that it’s a noop.There is however another thing that is definitely not good style. The way you use explicit parameters for the various type of notes. If when you finish this somebody comes and tells you “we have added five hundred dollar bills and we won’t bother filling in twenty dollar bills”, you’ll have to modify everything. You should generalize instead. Have array of values and array of counts…