DEV Community

loading...
Cover image for Vending Machine -Computational Thinking 101 | Beginner

Vending Machine -Computational Thinking 101 | Beginner

wahidd profile image David Wahid ・3 min read

A lot of the times people think of programming as something very hard to learn and impossible. I say it is only a matter of how determined and devoted you are! People spend tremendous amounts of time playing the most challenging games. They become experts and even beat those who spent years to come up with algorithms for that game. It is only a matter of determination!

I have decided to show how computational thinking and programming can be so much fun, while solving some real-life problems.

Let’s dig in!

Vending Machine

There are 3 types of drinks available in the Vending Machine.

  1. Americano — 500₩

  2. Caffe Latte — 400₩

  3. Lemon Tea — 300₩

User selects the drink number, and inserts money. Vending machine accepts money only in multiple of 100 (eg. 200, 1300, 7100) and money must be enough to buy at least one drink.

Given that the drink is selected and correct amount of money inserted, we should make a program which calculates how many 500₩ and 100₩ coins to return. We must return least amount of coins!

Disclaimer: For this little program, we assume all inputs are correct!

Examples

Example includes 3 different cases of input/output.

Solution

We need 2 variables to get the user input for drink number and payment. Since both inputs are whole numbers, we use integer types.

Now, it is time to get the user input.

Let’s start the sweaty work and calculate the change and units to return.

  1. In plain English, the change is the amount of payment minus the cost of the drink. We need a whole new variable to hold the change amount. Also, the change depends on the drink selected, so we use **switch **statement to conditionally find the change.

By the way, we can print the drink name right here!

  1. To return least number of coins, we must return 500₩ coins as many times as possible, agree? To do that, we just need to divide change by 500 and take the whole part. Luckily for us, in C language if you divide integer by integer, you only get the integer result, which discards the floating part of the division!

  1. Next, we just have to find the remainder after we got the 500s, and calculate how many 100₩ coins are in that remainder. We can use modulo(%) operator to find the remainder after all the 500s. Then, use division one more time to find the 100s.

Finally, we just have to print our calculations.

It is a real-life example of computational thinking to solve life problems.
I hope you enjoyed and learnt something. I am open for comments and discussions!

Here is a link to complete code. Go nuts and play around with it!

https://repl.it/@codwiznet/VendingMachine

Discussion (0)

pic
Editor guide