The Modulo Operator
Although modulus and modulo are often used interchangeably, there is a difference between the two depending if you are doing math or writing computer programs. I am okay if you use them interchangeably, in fact you may catch me saying modulus.
The Modulo Operator
The modulo operator is also a multiplicative operator. The modulo operator, which is the percent sign ( % ) gives you the remainder after two numbers are divided.
How Modulo Works
The modulo operator automatically divides and then returns the remainder. In business, we might use modulo to solve a problem like this: There are 15 bins in my warehouse. I want to store 2014 items. If I divide the items equally into the 15 bins, how many items are left over? 2014 modulo 15 is 4. My answer would be, there are 4 items left over.
Please review the below Java code snippet that could be used to solve this problem.
int items = 2014;
int bins = 15
int result = 0;
// Java Modulo operator
result = items % bins;
System.out.println("items % bins is " + result);
Another common business use for modulo is to determine if a number is odd or even. Any even number modulo 2 results in zero. Please study the below Java code snippet that could be used to solve this problem.
int evenNumber = 0;
int evenResult = 0;
int oddNumber = 0;
int oddResult = 0;
final int TWO = 2;
evenNumber = 14;
evenResult = evenNumber % TWO;
oddNumber = 15;
oddResult = oddNumber % TWO;
System.out.println("evenNumber % TWO is " + evenResult);
System.out.println("oddNumber % TWO is " + oddResult);
What you Learned
- You learned the the percent symbol (
%) does two things in one step:- First is divides two numbers
- Second it gives you the remainder of that division
- Modulo can come in handy for determining if a number is odd or even
Assignment Information
See Blackboard for assignment preparation tasks and assignment details.
What's next?
This is the last chapter in the Math Operators Unit. If you need help or have questions, do not hesitate to contact me.