Adding Data to the Calculator
We can wrap up with program with a couple of final changes. Firstly, we can add in a loop and allow the user to add more data to the array. Then in the final step we can look at also removing values from the array. These will be great features to help us explore arrays.
Adding a loop into main
If we add a loop to main, after populating the array, we can give the user options to change the values in the array and recalculate the statistics. Have a go at adding a menu to let the user add, remove, and view the data, calculate the statistics, and quit.
This is what I used for this:
Adding data
As with most of our code, each new action is likely to be coded in a new function or procedure which may in turn need additional functions and procedures to help implement its logic. So, for this we will create an add_data
procedure.
Add data
could accept the number data by reference, so that it can change the array and size details in the struct.
When you do this, you want to think of any cases where things may go wrong. Now, there are a couple that I can think of. Firstly, we need to make sure that we have not already run out of space in the array. We can only add new data if there is space for that data. We can guard against this with a simple if statement at the start of the add data
code. If there is no space, then we can output an error message and return.
In add data, we can then use the current size to determine where to store the data in the array. We can use the data.size
value as the index, as the size is one larger than the current highest index.
Have a go at coding this up yourself.
Now this got me thinking of another issue. It is a bit more tricky, as you have to think about providing invalid data to make this happen.
What would happen if data.size
became negative? While we protected against this in populate_array
, something may go wrong elsewhere or the data may become invalid due to a bug.
Have a go at fixing this code. Check if data.size
is negative, and set it to 0 before adding the value.
When you have added this in, update main to call this when the user chooses that option. Check that you can add values, but not exceed the maximum number.