Over the Christmas holidays, I did some independent learning and looked at the coding workshops and lectures on our Moodle page. I learned all about Modulus operators and how they can be used in games.
I also wrote out some code that displays it clearly
I started out by initialising three variables and then printed out variable "int c" to the console.
The "%" sign is a modulus operator (also known as a modulo). This operator treats the sum as a normal division, but instead of giving you the actual answer, it gives you the remainder.
My code says "int c = a % b". This means that 'c' is equal to 10 / 3. This sum would give you the answer of 9 remainder 1. However, due to the Modulo operator being used instead of a regular '/' division operator, the answer printed to the console would be 1. As the modulo operator will always provide the value of the remainder instead of the actual sum.
Below that I used a simple "if else" statement to print "C is an odd number!" if the sum is equal to 1.
If I were to change integer A's value to a 9, the following would print to the console: (see image below)
The answer has become zero as there is no remainder. 9 / 3 = 3 remainder 0. Zero is an even number!
Learning how to use modulo operators is useful for games where you implement dice mechanics. As you can then use mechanics that benefit or negatively impact a player depending on whether they've rolled an even or odd number.
Did you like this post? Tell us