We will continue working through the CS50 Problem Set from last week where we were learning to code in the C programming language. In this post, I will go over my solution to the cash problem in Problem Set 1. The problem presented here, is that we want to know how many coins a person will receive from the cashier given an amount. We also need to account for the fact that the cashier will want to produce the least amount of coins possible. For instance, if the cashier is given $4.00 on a bill of $3.42, the cashier will want to give the customer back 2 quarters, 1 nickel , and 3 pennies. So the output from our code should be 6.

The first thing that I wanted to do in this problem was create some variables for all of the coins that our cashier will be giving back to our customer. Secondly, I created a variable changeOutput that will act as the counter for the number of coins. Like the last solutions, we want to prompt the user while the input is invalid. This way, we will make sure the user inputs what we want. In this case, a positive floating point number.

The next thing I want to do is change the cents from a float to an integer to make the arithmetic a lot easier. We have to be careful here because when we convert from a float to an integer we risk loosing some cents because of a rounding issue. Therefore I multiply the input by 100 before I round and convert to an integer. This technique allows us to avoid any rounding issues.

Next, I created for loops for each of the coin variables I made earlier to count how many of each I will need. Notice that the order here is important. If, for instance, I put dimes before quarters I would get more dimes than I need and no quarters.  Each of these for loops operates in a similar fashion. While the cents variable is greater than or equal to the coin in question, it will subtract that value from the cents variable and add to our counter. Notice, you could also use modular arithmetic to solve this problem as well, though it may be a little more tricky.

Finally, after we have counted all of the coins out, our final step is to print the output to the user. I hope this helps you find your own solution to the problem. Keep plugging away at the course work and keep learning. If you have any questions about the material I have discussed, or you just want to connect, click on the Contact tab. If the content helped you, please return the favor by posting on your favorite social media site by simply clicking one of the buttons below. As always…Happy Programming.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s