A function has an input (the parameters), an output (return value and maybe parameters passed by pointer) and an algorithm that generates the output from the input.
Sometimes function do not really have an input or output like your superflous PrintDisplay
. This is generally okay if you make your code more readable/ better organized that way. Your function is superflous because you make a function (which has four lines) for a simple one line statement. Not inherently bad but superflous.
The return value "appears" at the position where the function call was made. So if you do
input = GetChange();
input
will be set to the return value of GetChange
.
You fixed this after Daves answer, but didn't see that all your Get...
functions also have a return value you just ignore in your code.
So by fixing all of them your code should work (or not see edit).
All your functions (except PrintResult
and the textinput) are basically oneliners. And
They reduce to
int GetCoins(int cents, int coin)
{
return cents / coin;
}
int GetNewChange(int cents, int coin)
{
return cents - coin;
}
So an improved program (in your design) would look like this then:
int main()
{
int leftover_change;
printf("Enter an amount to calculate change: ");
leftover_change= GetChange();
int FiftyCentAmount = GetCoins(leftover_change, 50);
leftover_change = GetNewChange(leftover_change, 50);
int TwentyCentAmount = GetCoins(leftover_change, 20);
leftover_change = GetNewChange(leftover_change, 20);
int TenCentAmount = GetCoins(leftover_change, 10);
leftover_change = GetNewChange(leftover_change, 10);
int FiveCentAmount = GetCoins(leftover_change, 5);
leftover_change = GetNewChange(leftover_change, 5);
PrintResult(FiftyCentAmount, TwentyCentAmount, TenCentAmount, FiveCentAmount);
if(leftover_change >0)
{
printf("there are %d cents left
", leftover_change);
}
system("pause");
return 0;
}
This still vioaltes the DRY concept (Dont repeat yourself) you could fix this (at least partially) by replacing the magic numbers with defines or const variables.
Even better would be a loop that iterates through the different coins. But this needs a bit more thinking and the use of arrays.
edit: I did not check the algorithm in the first place, and my scanf
reduction was bullshit but I was in a hurry so here a version that works. To make this answer complete, but as Dave said you should check your algorithm before you implement it.
int GetNewChange(int cents, int coin)
{
return cents % coin; //this is the modulus operator
}