This is an optional tour - use it to extend your understanding.
Giving change
We can use a flowchart to help us capture the sequence we need to perform in the change calculator.
When we code this we want to try to avoid duplication. Instead of repeating code, over and over, to give different change values, we can use control flow and code this up as general instructions.
This will be a common theme as we go forward. In order to create more interesting programs, we need to start using data together with the control flow statements. By doing this you can then change the data, and the processing should work with the new context.
For example, the change calculator currently works with Australian currency. If we could move this to pure data, then we could shift to American currency by just changing the data that informs this control flow.
Steps to give change
Let’s quickly think through the steps needed to give change. We can think of this as the following sequence.
Notice that each coin we give has the same steps. The only difference is the value of the coin and the text that is used when this is output. For example, with the 20c coin we need to know the value of the coin is 20 and the text is “20c”. So the steps can be:
This can be implemented in C# using variables as:
Notice this does not mention any specific coin or literal value, and allows us to work with any coin value.
Let’s put this in our code and calculate how many $2 coins to give.
Create the toGive, coinValue, and coinText variables.
After calculating the change value, initialise coinValue to 200 and coinText to “$2”. Then add the above code to calculate how many coins to give.
Compile and run your program, and then test that it can output the right number of $2 coins for a range of different change values.
When you run this you should see something like this:
Now, add in constants for each of the coin values, and we can add in a constant for the number of coins.
Now we can repeat the code to calculate the change, once for each coin. We can use a for loop to achieve this, as there is a set number of coins that we need to iterate through. This gives us the following pseudocode:
Have a go at adding this loop in, and for the moment it can give $2 multiple times. You will need to add in an i variable to keep track of the number of times through the loop.
When you run this it should output 6 coin values, but they are all $2.
To wrap this up we need to set the values for coinValue and coinText. We can use the control variable i to determine which values to use. When i is 0, we need to use $2, when it is 1 we need to use $1, and so on.
This is a great example of where we can use a case statement. The following pseudocode shows how this might look:
Have a go at adding this logic to your program.
Compile and run your program, making sure that it outputs the right change for the values you enter.