Other than the read_integer function, the code in the change calculator has two main actions. We have the overall process of reading the cost and amount paid, and we have giving change. So we can split the code into these two parts. It will help more clearly show these parts, and will allow us to work within a smaller procedure.
Give Change
The give change logic is coded within an if statement in main at the moment. This code can be cut and pasted into its own procedure. You will need to move the constants either into the procedure, or globally and above the procedure so that they are available to this code.
This procedure can now take care of giving change, when change needs to be given. This means we do not have all the other code here, just the code to give change, The code for the “again” loop, the code to read in the details, and the test to see if change needs to be given remain in main. Now both main and give change have a clear, and more specific, purpose.
Have a go at separating this out from the other code.
Main Code
The code inside main can now focus on the overall process: get the details from the user, give change if needed, and repeat if needed. The logic for this is shown below. It is relatively straightforward now that the change calculations are moved out.
Have a go at adjusting this code yourself. Move the change calculating code out of main into a give_change procedure. You will also need to move the constants up to that procedure, or make them global.
Remember you can check out our version of the code in the Campsite Reflection.